Reputation: 3217
I am trying to create a sub-component in JSX which is a list of items with an onClick event and an event handler. The event handler is never called. Please help me figure out what i am doing wrong.
EDIT: Thanks to @FakeRainBrigand, i found out the problem was elsewhere. I figured out that when I hide/show the sub-component using an event handler in the parent component, it stops triggering the onClick event handler, since the parent's hide operation triggers. JSBIN
The JSX code.
var FilterList = React.createClass({
handleClick: function(e){
console.log(e);
},
render: function(){
var ListItems = this.props.data.map(function(item){
return (
<li key={item.id} className="filter-item" onClick={this.handleClick}>
<span key={'img'+item.id} className={item.imgClass}></span>
<span key={'text'+item.id} className="item-text">{item.name}</span>
</li>
)
}, this);
return (
<div className="filter-list">
<ul>
{ListItems}
</ul>
</div>
);
}
});
The generated JS code:
var FilterList = React.createClass({displayName: 'FilterList',
handleClick: function(e){
console.log(e);
},
render: function(){
var ListItems = this.props.data.map(function(item){
return (
React.DOM.li( {key:item.id, className:"filter-item", onClick:this.handleClick},
React.DOM.span( {key:'img'+item.id, className:item.imgClass}),
React.DOM.span( {key:'text'+item.id, className:"item-text"}, item.name)
)
)
}, this);
return (
React.DOM.div( {className:"filter-list"},
React.DOM.ul(null,
ListItems
)
)
);
}
});
Upvotes: 4
Views: 4206
Reputation: 184
maybe use callback function. use callback on onclick
like this:
var FilterList = React.createClass({
handleClick: function(e){
console.log(e);
},
render: function(){
var ListItems = this.props.data.map(function(item){
return (
<li key={item.id} className="filter-item" onClick={() => this.handleClick}>
<span key={'img'+item.id} className={item.imgClass}></span>
<span key={'text'+item.id} className="item-text">{item.name}</span>
</li>
)
}, this);
return (
<div className="filter-list">
<ul>
{ListItems}
</ul>
</div>
);
}
});
Upvotes: 0
Reputation: 71
What happens if you add a self = this; and change the this.handleClick to self.handleClick?
render: function() {
self = this;
var ListItems = this.props.data.map(function(item){
return (
<li key={item.id} className="filter-item" onClick={self.handleClick}>
<span key={'img'+item.id} className={item.imgClass}></span>
<span key={'text'+item.id} className="item-text">{item.name}</span>
</li>
)
}, this);
Upvotes: 1
Reputation: 3638
You want to make your server/ajax call in componentDidMount, not componentWillMount. You can check out why in the documentation here React Component Lifecycle
Upvotes: 0