Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  39] [ 4]  / answers: 1 / hits: 16182  / 9 Years ago, sun, july 26, 2015, 12:00:00

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

});

More From » reactjs

 Answers
6

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

[#65670] Thursday, July 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
paola

Total Points: 675
Total Questions: 115
Total Answers: 95

Location: Laos
Member since Tue, Jul 7, 2020
4 Years ago
;