EdG
EdG

Reputation: 2351

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>
    );
}
}

Upvotes: 2

Views: 86

Answers (2)

Funk Soul Ninja
Funk Soul Ninja

Reputation: 2193

WitVault is correct. You are passing the result of the function rather than the function itself.

Also, if you have a lot of props to pass down you can pass all the props by using the spread operator on the child component:

<ChildComponent {...this.props} />

Upvotes: 1

WitVault
WitVault

Reputation: 24140

<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)}

Upvotes: 3

Related Questions