+ 1
When to use state and when to use props in react?
It's always confusing for me use props and stats in react. Actually, I can not get the concept of difference between state and props properly.
1 ответ
+ 2
State are the variables you define in your constructor and you would use this.state to get them when you are located IN THE SAME component it was set. Props are the variables you pass down to child-components.
class Parent extends React.Component {
this.state = {
nameOfState: 'This is a state',
}
render() {
return (
{this.state.nameOfState} //will render the string 'This is a state'
<ChildComponent nameOfProp="This will be a prop in the child" /> //renders child with 1 prop
)
}
}
You use props to pass down information to child-components from parents, and now you can use this.props to collect the props you passed down.
class ChildComponent extends React.Component {
//constructor
render() {
return (
{this.props.nameOfProp} //will render the string 'This will be a prop in the child'
You could also declare new states in the child-component or even pass the props down to a child-component of the first chid.
<GrandChildComponent sendThisToGrandChild={this.props.nameOfProp} />
)
}
}
class GrandChildComponent extends React.Component {
//constructor
render() {
return (
{this.props.sendThisToGrandChid} //will render the string 'This will be a prop' - all the way from parent!
)
}
}