Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override event handler function of child component from parent component in react.js

/** @jsx React.DOM */

var Button = React.createClass({
  handleClick: function(){
    console.log(' FROM BUTTON')
  },
  render: function() {
    return <input type='button' onClick={this.handleClick} value={this.props.dname}/>;
  } 
});

var Text = React.createClass({
  render: function() {
    return <input type='text' onClick={this.handleClick} value={this.props.ival}/>;
  } 
});


var search = React.createClass({
  handleClick: function() {
    console.log('searching')
  },
  render: function(){
    return (
      <div>
        <Text/>
        <Button dname={this.props.dname} onClick={this.handleClick} />
      </div>
    );
  }
});

React.renderComponent(<search dname='Look up' fname='Search'/> , document.body);

I have created a button and text component and included them in a search component now i want to override the default handleClick event of button with search component's handler. But this.handleClick is pointing to button component's event handler.. please help.. i need FROM SEARCH on click instead i got FROM BUTTON..

like image 235
Softwareddy Avatar asked Jan 17 '14 07:01

Softwareddy


People also ask

How do you pass event from child component to parent in React?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.


2 Answers

You are 99% percent there.

React uses a one-way data-flow. So, events on nested components will not propagate to their parents.

You must propagate events manually

Change your <Button>s handleClick function to call the this.props.handleClick function passed in from it's <Search> parent:

var Button = React.createClass({
  handleClick: function () {
    this.props.onClick();
  },

  ...

});

Attached is a fiddle of your original post, with the required change. Instead of logging FROM BUTTON, it will now alert searching.

http://jsfiddle.net/chantastic/VwfTc/1/

like image 153
chantastic Avatar answered Oct 11 '22 22:10

chantastic


You need to change your Button component to allow such behaviour:

var Button = React.createClass({
  handleClick: function(){
    console.log(' FROM BUTTON')
  },
  render: function() {
    return (
      <input type='button'
        onClick={this.props.onClick || this.handleClick}
        value={this.props.dname} />
    );
  }   
});

note the onClick={this.props.onClick || this.handleClick}.

That way if you pass an onClick prop when instantiating Button it will have a preference over the Button's handleClick method.

like image 37
andreypopp Avatar answered Oct 12 '22 00:10

andreypopp