Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  70] [ 5]  / answers: 1 / hits: 96055  / 8 Years ago, sun, june 5, 2016, 12:00:00

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.


More From » reactjs

 Answers
6

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

[#61906] Wednesday, June 1, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daytonm

Total Points: 519
Total Questions: 83
Total Answers: 89

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;