0

Let's say you have a Parent component which defines a method:

    class Parent extends Component {
     handleX() {
       this.setState({ x: true });
     }
   }

If I pass this function as props to Child and call it on for example a button click, which state will be updated - Child or Parent? What is the correct way to use this?

Alex5207
  • 464
  • 2
  • 7
  • 16

1 Answers1

1

Neither. If you want to update the parent state, you need to either hard-bind it or change it to a public class field (handleX = () => { this.setState({ x: true })}). But you will not be able to update the child state because of how this works.

handleX = () => {
  this.setState({ x: true })
}

or

<Child handleX={handleX.bind(this)} />

or

<Child handleX={() => handleX()} />

If you want to learn more about how this works in JS, refer to this question, or google it, there are tons of articles out there. Personally, I found Kyle's You don't know JS - This and object prototypes more than helpful

Ionut Achim
  • 937
  • 5
  • 10