React is a javascript library that can be used to write single-page applications or mobile apps. React works by using components that can render HTML if necessary. These components can hold their own data in an object called ‘state’ or can receive data passed as ‘props’ from their parent component.
What is state?
It is a special built-in object of React that allows components to create and manage their own data.
Here is an example of how state is used:
class Example extends React.Component {
state = {count: 0} render() {
return (
<div>
<p>{this.state.count}</p>
</div>
)
}
}
How to update state?
A state can be updated using the method setState()
.
class Example extends React.Component {
state = {count: 0}increment = () => {
this.setState({
count: this.state.count +1})
}render() {
return (
<div onClick={this.increment}>
<p>{this.state.count}</p>
</div>
)
}
}
A change in the state happens based on user input, in the example above, triggering an event, each time the user clicks on the div the count will increment by 1. Every time the state changes React gets informed and immediately re-renders the DOM rendering the new state.
What are Props?
Props are short for properties and they are used to pass data between components.
How to pass data with props?
Here is how you pass props:
class Parent extends React.Component {
render(){
return(
<Child name={"first name"}/>
)
}
}const Child = (props) => {
return <p>{props.name}</p>
}
to pass a prop to a component we add them as attributes:
<Child name={"first name"}/>
We pass data with props like giving an argument to a function and use dot notation to access the data:
return <p>{props.name}</p>
For me, understanding states and props was a bit difficult, especially props, I had a lot of difficulties understanding how to pass data from one component to another, but now I feel comfortable using state and props, so I hope that this article can help someone understand state and props better.