React.JS this.state undefined

I currently have this component in React.JS that shows all the images passed to it in an array, and onMouseOver shows the button below. I planned to use setState to check if the variable hangs, if it is true or false, and toggle the button of this image accordingly, however I keep getting the following error:

Uncaught TypeError: Unable to read state property undefined

var ImageList = React.createClass({ getInitialState: function () { return this.state = { hover: false }; }, getComponent: function(index){ console.log(index); if (confirm('Are you sure you want to delete this image?')) { // Save it! } else { // Do nothing! } }, mouseOver: function () { this.setState({hover: true}); console.log(1); }, mouseOut: function () { this.setState({hover: false}); console.log(2); }, render: function() { var results = this.props.data, that = this; return ( <ul className="small-block-grid-2 large-block-grid-4"> {results.map(function(result) { return( <li key={result.id} onMouseOver={that.mouseOver} onMouseOut={that.mouseOut} ><img className="th" alt="Embedded Image" src={"data:" + result.type + ";" + "base64," + result.image} /> <button onClick={that.getComponent.bind(that, result.patientproblemimageid)} className={(this.state.hover) ? 'button round button-center btshow' : 'button round button-center bthide'}>Delete Image</button></li> ) })} </ul> ); } }); 
+8
javascript reactjs
source share
2 answers

You get an error because you save the reference to this in the that variable that you use to refer to event handlers, but you DO NOT use it in a triple expression to define the className for the button element.

your code:

 <button onClick={ that.getComponent.bind(that, result.patientproblemimageid) } className={ (this.state.hover) ? // this should be that 'button round button-center btshow' : 'button round button-center bthide'}>Delete Image </button> 

When you change this.state.hover to that.state.hover , you will not get an error.

On the side of the note, instead of storing the this reference in a variable that you can simply pass the context parameter to the map() method .

 results.map(function (result) { // }, this); 
+5
source share

In ES5 format, you cannot set this.state directly

 var ImageList = React.createClass({ getInitialState: function () { return { hover: false }; }, render : function(){ return(<p>...</p>); }); 

However, with the new ES6 syntax, you can essentially control this:

 class ImageList extends React.Component{ constructor (props) { super(props); this.state = {hover : false}; } render (){ ... } } 
+3
source share

All Articles