React. js-Explaining Props and State

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?

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?

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?

How to pass data with 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store