January 18, 2017

React pass parameter to parent component or call parent function on ES6

sometime you will need to call parents function on react component, the problem in ES6 is that all functions are not bind with this, so you will need to do manually, below is a simple toggle function that you will call from Child component, notice that in order to call the parent's method, you will have to pass in the function as a property to Child component then trigger from child onClick method, notice that I have bind this to this.props.parentToggle, by default in ES6 react decided not to auto bind this like what usual javascript does, so we have to do it manually.

Now imaging that you don't want to just call a simple function, you want to pass in some parameters from child to parent and change some states to parent, so here is the only way you can do without any other plugins or so...
Lets use 0 counter and we want to increase each time pressed from Child button.
Lets add a constructor Parent componetnt and initialised a state, can be anything, we user "counter" here.

then I want to show the counter on the screen, so lets render this state on the container, remember to wrap the elements with something, react will not render same level jxs,

you should be able to see a 0 on screen with "I am child" and a toggle button, lets create a counter variable on Child too in constructor,

so when clicked on child toggle button, this counter should plus 1, lets create a method to add this counter, and pass it to Parent component:

which means clicking on the toggle button, I will need to trigger this method, so lets change the onClick to

Since we mentioned earlier ES6 method does not have any this bind to it, we will need to bind ourself manually again from Child constructor, lets add this binding in Child constructor, which will looks like this:

When you add up all scripts you should be able to see as my embed source below, try it out and enjoy.

Below is another demo if you want to pass the counter down to Child component: