Skip to content Skip to sidebar Skip to footer

How To Change A Component State When I Click On A Button That Is On Another Component

I have a button and I need for the button to change a parent state value on click. I know there are tons of questions like this but I swear I just can't understand it. I have tried

Solution 1:

The way to do it is by defining a call back function as a prop that is passed from the parent to the child component.

When you click a button in the child component, this callback function will be executed, and since it is in the parent, it can call setState that changes the state in the parent.

There are indeed many examples around on how to define such a callback. For example:

In your code, I believe that the following will work:

In ProductPage:

<NinjaH2R product={product} 
  callback={this.ninjaHandler}
  product={product}
/>

ninjaHandler = () => {
  this.setState({ toggle400: true });
}

In NinjaH2R:

<buttononClick={this.props.callBack}>
  Ninja 400
</button>

Post a Comment for "How To Change A Component State When I Click On A Button That Is On Another Component"