Gaurav Jagtap Gaurav Jagtap - 7 months ago 35
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){
if (confirm('Are you sure you want to delete this image?')) {
// Save it!
} else {
// Do nothing!
mouseOver: function () {
this.setState({hover: true});

mouseOut: function () {
this.setState({hover: false});
render: function() {
var results =,
that = this;
return (
<ul className="small-block-grid-2 large-block-grid-4">
{ {
<li key={} 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>




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:

  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

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. (result) {
}, this);