I have a child with a touchable component inside a parent, I would like to setState() of both the child and the parent when pressing the touchable component. Is there a good way to accomplish this?
Asked
Active
Viewed 461 times
0
-
The best way to accomplish this is to keep the state only in parent and pass it as props to the child and not store it at multiple places. You should have a single source of truth. Check this answer on how to pass data from child to parent https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs/38397755#38397755 – Shubham Khatri Jan 04 '18 at 16:58
1 Answers
3
If the data affects both the child and parent component, then the data should be moved into the parent's state then passed down to the child component via props. So in your instance I would suggest moving the state up from the child component into the parent component. Then create a function that sets the state inside the parent component and pass that function to the child component via props.
For example:
class ParentComponent extends React.Component {
state = {
isPressed: false
}
toggleIsPressed = () => {
this.setState({ isPressed: !this.state.isPressed })
}
render(){
return(
<ChildComponent toggleIsPressed={this.toggleIsPressed} imPressed={this.state.imPressed} />
)
}
}
const ChildComponent = ({ toggleIsPressed, imPressed }) => {
return(
<button onClick={toggleIsPressed}>{ isPressed ? "I'm pressed" : "I'm not pressed"}</button>
)
}

MEnf
- 1,482
- 1
- 12
- 18
-
Thank you. This might not be an ideal solution if there are, say, 20 buttons (you'd need to keep 20 different states), but I suppose a different approach would be needed then altogether. – Dror Bar Jan 07 '18 at 07:17