Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React : Pass function to child component [duplicate]

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.

like image 705
onedkr Avatar asked Jun 05 '16 00:06

onedkr


1 Answers

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 
like image 136
omarjmh Avatar answered Sep 29 '22 07:09

omarjmh