javascript - React: Getting an object on click -


i have array of objects passed property list maps them <li>.

i able, individual item, click on item list, , receive object , assign root component's state - pass on 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!

pass callback function menu component prop , use function.prototype.bind() partially apply relevant post object 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


Comments