Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
);
}

});
like image 986
Gaurav Jagtap Avatar asked Jul 26 '15 11:07

Gaurav Jagtap


2 Answers

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);
like image 175
danillouz Avatar answered Oct 05 '22 11:10

danillouz


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 new ES6 syntax you can essentially manage this:

class ImageList extends React.Component{
constructor (props) {
  super(props);
  this.state = {hover : false};
}
render (){ ... }
}
like image 23
max_new Avatar answered Oct 05 '22 11:10

max_new