Ad

React-js Subcomponent Onclick Event Does Not Get Invoked

- 1 answer

The Container component is the main component ,which in-turn invoked the rendering of User Component. In user render method the <li> items have onClick event.

The onClick events are getting invoked on page load and then never gets invoked the click event.

Container = React.createClass({

mixins: [ReactMeteorData],

getMeteorData(){
    return{
        currentActiveUsers:ActiveUsers.find({}).fetch()
    };
},

getCurrentActiveUsers(){
    return this.data.currentActiveUsers.map((user) => {
        return <User key={user._id} user={user} />
    }); 
},

render(){
    return(
        <div className="container">
            <div className="container-fluid">
              <div className="row">
                <div className="col-xs-1 col-md-2 col-lg-3 columnBorder">
                    <ul>
                        {this.getCurrentActiveUsers()}
                    </ul> 
                </div>
              </div>
            </div>
        </div>
        );
}

}); User = React.createClass({

propTypes:{
    user:React.PropTypes.object.isRequired
},

initiate(){
    console.log("initiated");
},

render(){
    return(
        <li onClick={this.initiate()}>
            {this.props.user.username}
        </li>
    );
}

});

Ad

Answer

You are invoking the event at the time of defining the onClick. Instead, you need to bind the onClick to the function:

initiate(){
    console.log("initiated");
},

render(){
    return(
        <li onClick={this.initiate}>
            {this.props.user.username}
        </li>
    );
}

So, simply remove the function call () from the this.initiate().

Otherwise, you are attempting to bind the result of console.log to onClick.

Ad
source: stackoverflow.com
Ad