I was watching a Pluralsight course on React and the instructor stated that props should not be changed. I'm now reading an article (uberVU/react-guide) on props vs. state and it says
Both props and state changes trigger a render update.
Later in the article it says:
Props (short for properties) are a Component's configuration, its options if you may. They are received from above and immutable.
getInitialState
?Both state and props in react are used to control data into a component, generally props are set by parent and passed to child components and they are fixed throughout the component. For data that is going to change, we have to use state.
Props are arguments passed into React components. Props are passed to components via HTML attributes. props stands for properties.
Props are immutable, while state is mutable Although a component is not allowed to change its props, it is responsible for the props of its child components down the component tree. On the other hand, state is mutable.
Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child within the render method of the parent as the second argument to React.createElement()
or, if you're using JSX, the more familiar tag attributes.
<MyChild name={this.state.childsName} />
The parent's state value of childsName
becomes the child's this.props.name
. From the child's perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:
this.setState({ childsName: 'New name' });
and React will propagate it to the child for you. A natural follow-on question is: what if the child needs to change its name prop? This is usually done through child events and parent callbacks. The child might expose an event called, for example, onNameChanged
. The parent would then subscribe to the event by passing a callback handler.
<MyChild name={this.state.childsName} onNameChanged={this.handleName} />
The child would pass its requested new name as an argument to the event callback by calling, e.g., this.props.onNameChanged('New name')
, and the parent would use the name in the event handler to update its state.
handleName: function(newName) { this.setState({ childsName: newName }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With