onedkr onedkr - 6 months ago 39
Javascript Question

React : Pass function to child component

I try to pass a function to my child component. For each child component when the user click on them, the onclick function will be call. This onclick function is written into the parent component.

Parent component:

class AgentsList extends React.Component {
constructor(props) {
super(props);
}

handleClick(e) {
e.preventDefault();
console.log(this.props);
}

render() {
const { agents } = this.props;

...

var agentsNodes = agents.map(function(agent, i) {
if(agent.id_intervention == "") {
return (
<Agent agent={agent} key={i} ticket={t} id={row_names} onClick={this.handleClick.bind(this)} />
);
}
});
return (
<div id="agents">
<div className="agents-title">
<h3>Title</h3>
</div>
{agentsNodes}
</div>
);
}
}


Child component:

class Agent extends React.Component {
constructor(props) {
super(props);
}

render() {
const { agent, t } = this.props;

return (
<Link to='/' onClick={this.props.onClick}>
...
</Link>
);
}
}


At this line :
<Agent agent={agent} key={i} ticket={t} id={row_names} onClick={this.handleClick.bind(this)} />


It say that handleClick is not defined ...
How can I sovle this problem ?

Thank's for your answer.

Answer

You need to bind Agents to AgentsList: Here's a quick example with your code, I had to get rid of some stuff, but you get the idea:

http://jsfiddle.net/vhuumox0/19/

var agentsNodes = agents.map(function(agent, i) {
  if(agent.id_intervention == "") {
    return (
      <Agent agent={agent} key={i} ticket={t} id={row_names} onClick={this.handleClick.bind(this)} />
    );
  }
}, this); // here
Comments