user3761761 user3761761 - 26 days ago 8
React JSX Question

Trouble in passing prop to child

I am having problem with passing props to child element. I have a parent which renders the child(four times) having button. I want to execute "console.log(id);" everytime I click the button. But problem is onClick gets executed even if I don't click the button. So in console I can see it gets printed all in once. Here is my code. tagsBrief_array is a array of json objects.

Parent Component

export default class TagsBrief extends Component{
handleClick(id){

console.log(id);
}
render() {
var populate = tagsBrief_array.map((value)=> {
return(
<TagBriefItem id={value.id} onclick={this.handleClick} description={value.tag_name} percent={value.tag_percent}/>)
});
return (
<MuiThemeProvider>
<div className="tagsBrief">
{populate}
</div>
</MuiThemeProvider>
);
}
}


child Component

export default class TagsBriefItem extends Component {

render() {
return (
<MuiThemeProvider>
<button onClick={this.props.onclick(this.props.id)} style={{backgroundColor: "#293C8E"}} className="tagsBriefItem">
<h2 style={styles.headline}>{this.props.description}</h2>
<h3 style={styles.headline}>{this.props.percent}</h3>
</button>
</MuiThemeProvider>
);
}
}

Answer
<button onClick={this.props.onclick(this.props.id)} style={{backgroundColor: "#293C8E"}} className="tagsBriefItem">
    <h2 style={styles.headline}>{this.props.description}</h2>
    <h3 style={styles.headline}>{this.props.percent}</h3>
</button>

Here you are passing result of onClick prop not a function. That's why you are seeing logs as a result of call of onClick which in turns calls parent's handleClick.

you can change that to onClick = { () => this.props.onclick(this.props.id)}