Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we attach click handlers to custom child components

Tags:

reactjs

I was trying to add a click handler to my own child component. In react chrome extension I was able to see the click handler as well.

But the click itself didn't work - wondering what did I miss.

Sample Code:

... 
render (
  <MySampleComponent onClick={this.handler} />
);
...
like image 386
Raja Avatar asked Mar 18 '14 03:03

Raja


People also ask

How can we pass an event handler to the child component?

To pass an onChange event handler to a child component in React: Define the event handler function in the parent component. Pass it as a prop to the child component, e.g. <Child handleChange={handleChange} /> . Set it to the onChange prop on the input field in the child.

How can you pass event handler to component?

Passing Event Handler to Subcomponent The Address component is using the destructuring assignment { type, houseNo, clickHandler } to access the passed prop values directly. The clickHandler is a function to handle clicks, which is being passed to the onClick attribute.

Can we use same event handler on multiple components?

Absolutely yes! You can fire a lightning event and that will be handled in each & every component which has a handler defined in it.

How can we pass Props parent to child components?

To pass data from a child component to its parent, we can call a parent function from the child component with arguments. The parent function can be passed down to the child as a prop, and the function arguments are the data that the parent will receive.


2 Answers

MySampleComponent can take whichever props it wants; components don't automatically copy props to their children. If you want to be able to add an onClick handler to MySampleComponent, then you can support this in the definition of that component:

var MySampleComponent = React.createClass({
  render: function() {
    return <div onClick={this.props.onClick}>...</div>;
  }
});
like image 92
Sophie Alpert Avatar answered Oct 08 '22 13:10

Sophie Alpert


You can add the handler from the samecomponent or call it through props. Below code looks for onClick param in props. If nothing is passed, then it goes for default handler in the component(clickHandler).

var MySampleComponent = React.createClass({
  clickHandler: function(){
       // write your logic
  },
  render: function() {
    return <div onClick={this.props.onClick || this.clickHandler}>...</div>;
  }
});

and while using this in another component use it as below

...........
handler: function() {
   // write your logic 
},
render {
  var self = this;
  return (<MySampleComponent onClick={self.handler} />);
 }

......
like image 30
Softwareddy Avatar answered Oct 08 '22 13:10

Softwareddy