0

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!

2
  • Sounds like Flux data flow and event emit is a good way to do it. Commented May 8, 2015 at 10:29
  • possible duplicate of React onClick problems Commented May 8, 2015 at 11:13

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! Say, why wouldn't onClick={this.props.onClick.bind(this, post)} work? Why Bind()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.