Gaurav Jagtap Gaurav Jagtap - 3 months ago 17
Javascript Question

React.JS this.state is undefined

I currently have this component in React.JS which shows all the Images passed to it in an array and onMouseOver it shows a button below. I planed on using setState to check the variable hover if is true or false and toggle the button of that image accordingly however i keep getting the following error : Uncaught TypeError: Cannot read property 'state' of 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>
);
}

});


Thanks.

Answer

You get the error because you're storing the reference to this in a that variable which you're using to reference your event handlers, but you're NOT using it in the ternary expression to determine 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 won't get the error.

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

results.map(function (result) {
  //
}, this);