My problem is the following.
- I have a "BookShelf" component which contains a "Book" list.
- The parent (bookshelf) manage in its state a "selectedBook" property.
- When clicking on one child (book), I would like to update its parent selectedBook property.
- To achieve this, I use a function defined in the parent properties.
- But this method is never trigerred (I tried with a console.log('something') but it never shows.
See my code below :
setSelectedBook(index) {
this.setState({
selectedBook: index
})
},
getInitialState() {
return {
books: [],
selectedBook: null
}
},
componentDidMount() {
let component = this
$.ajax({
url: 'data/books.json',
success (data) {
component.setState({
books: data
})
},
error (err) {
console.log(err)
}
})
},
render() {
let component = this
var bookList = this.state.books.map(function(book, index) {
let selectBook = component.setSelectedBook.bind(component, index)
return (
<Book onClick={selectBook} data={book} key={index} />
)
})
return <div className="book-shelf">
{bookList}
</div>
}
Thanks in advance !
Bookcomponent triggersonClick? You need to triggerprops.onClick()explicitly inBookcomponentBookcomponent?onClickis just property on your custom component, react doesn't know what to do with it.