Data flow in React is top to bottom. Props are used to pass pieces of data down to child components. Props are read-only, so this data is immutable. State holds mutable data.
Generally, if multiple components require access to changing data, this shared state must be lifted up to a common parent component in order for all its children to have access to it. Props are then used to pass relevant data down.
But what if your child component needs to update the shared state?
You can pass a callback function down to the child that modifies state.
First, define a callback function in your parent component that modifies state:
class Parent extends Component {
constructor() {
super()
this.state = {
filter: 'featured'
}
}
handleChange = event => {
this.setState({
filter: event.currentTarget.value
})
}
Next, pass this function down as a prop to the child component:
render() {
return (
<div>
<Child handleChange={this.handleChange}/>
</div>
)
}
Finally, in your child component, bind the handle change function to an action:
import React from 'react';
const Child = (props) => {
return (
<div>
<button onClick={props.handleChange} value="recent" />
</div>
)
}
export default Child;
Now when the button in your child component is clicked, the filter value in your parent state will update!