jmurinello jmurinello - 2 months ago 9
React JSX Question

Required prop `onClick` was not specified // Cannot read property 'bind'

I'm trying to pass the 'handleWordClick' function to a component but I keep getting the error that the proptype was not specified. Also when I try to pass the prop with .bind

'this.handleWordClick.bind(this)'


...I get the error that cannot read property 'bind'.

This error maybe due to my lack of knowledge but would appreciate some help.

Thanks.

Here's the part of the code of the container:

handleWordClick: function () {
this.setState({ isModalOpen: true });
},

handleCloseModalClick: function () {
this.setState({ isModalOpen: false });
},

renderBookPage: function(which) {
var book = this.state.book;

return book[which].map(function (page, index) {
return <WordWrapper
key={index}
page={page}
onClick={this.handleWordClick} />
})
},


Here is the component that I'm trying to pass the 'onClick' prop:

function WordWrapper (props) {
return (
<span style={styles.cursorPointer} onClick={props.onClick}>{props.page.word}</span>
)
}

WordWrapper.propTypes = {
page: PropTypes.shape({
word: PropTypes.string.isRequired
}),
onClick: PropTypes.func.isRequired
}

module.exports = WordWrapper;

Answer

Try this

var _this = this;
return book[which].map(function (page, index) {
return <WordWrapper
  key={index}
  page={page}
  onClick={_this.handleWordClick} />
})

The reason for the error is, the this inside .map() refers to the map() not the React.createClass()

Comments