First off I Know about this thread: React onClick event on component
Is there not a way to do this directly to a React Component? That didn't seem to get answered in the thread. I know how i can add the attacked function a layer deeper but that is just extra connection code that makes it more brittle IMO. any change that it make to the ListItem level i would have to make to the interconnect. I imagine this getting much worse if am an nTh level child component trying to get back up to the master State.
My Case
Parent->List->ListItem
I need to have a click event on a list element trigger a function on the parent. I want to be able to click a ListItem component and have that onClick event come back up to Parent and update the state to trigger a rerender of a of a sibling component to List I have cut out a lot of boilerplate.
Parent Component wrapping it all. this is where i am using state to update my render views.
var Parent = React.createClass({
updateState:function(newCurrent){
this.setState({current: newCurrent});
},
render: function() {
return (
<div className="Parent" >
<Current this.state.current />
<List
list={this.state.list}
updateCurrentVideo={this.updateCurrentVideo} />
</div>
);
}
});
List here is the List Element described at the start, i would like to attach an onClick event to each ListItem ti pass its data back up to parent to update state.
Instead of attaching the event inside of the compoent and the having to pass the trigger like this. ListItem->List->Parent(). It would be nice to attach the listener while i .map through the children of List.
var List = React.createClass({
render: function() {
var list = this.props.list.map(function(item,index){
return (
<ListItem
onClick={ () => this.props.updateState(item) } />
)
}.bind(this));
return (
<div className="List">
{list}
</div>
);
}
});
The onClick attached at the component level doesn't appear to actually do anything. However if i change it to be like this and pass a prop down to the ListItem with a callback function then it magically works. So i guess my greater question this.
var ListVideos = React.createClass({
handleClick:function(data){
this.props.updateCurrentVideo(data)
},
render: function() {
var list = this.props.list.map(function(item,index){
return (
<ListItem
handleClick={this.handleClick(item) } />
)
}.bind(this));
return (
<div className="List">
{list}
</div>
);
}
});
And then Attach the onClick to the Component wrapper in the ListItem
var ListItem = React.createClass({
render: function() {
return (
<div className="ListItem" onClick={this.props.handleClick}>
// STUFF
</div>
);
}
});