Nir Benita
Nir Benita

Reputation: 511

React: Getting an object on click

I have an array of objects which is passed as a property to a list that maps them to <li>.

I would like to be able, for any individual item, to click on an item from the list, and receive that object and then assign it to the root component's state - so I could then pass it on to another child comp.

var Menu = React.createClass({
render: function() {
    return (<ul>
        {
            this.props.posts.map(function(post){
                return <li><a onClick={function(e){console.log(e)}}>{post.title}</a></li>
            })
        }
    </ul>)
}

})

https://jsfiddle.net/nbenita/yxw1z42q/

Thanks!

Upvotes: 0

Views: 2821

Answers (1)

Jonny Buchanan
Jonny Buchanan

Reputation: 62793

Pass a callback function into your Menu component as a prop and use Function.prototype.bind() to partially apply the relevant post object as an argument:

Updated fiddle: https://jsfiddle.net/yxw1z42q/2/

var Blog = React.createClass({
    getInitialState: function() {
        return {
            selectedPost:this.props.posts[0]
        };
    },
    onPostSelected: function(selectedPost) {
        this.setState({
            selectedPost: selectedPost
        });
    }
    render: function() {
        return (<div>
            <Menu posts={this.props.posts} onClick={this.onPostSelected} />
            <Post content={this.state.selectedPost} />
        </div>)
    }
})

var Menu = React.createClass({
    render: function() {
        return (<ul>
            {
                this.props.posts.map(function(post){
                    return <li><a onClick={this.props.onClick.bind(this, post)}>{post.title}</a></li>
                }, this)
            }
        </ul>)
    }
})

Further reading

Upvotes: 2

Related Questions