TypeError: Cannot read property 'state' of undefined with create-react-class
See original GitHub issueI am currently attempting to create a button which is red with the text “Yes” that when you click on it the button changes to a green color with the text “Confirm?” before the final stage in which an action takes place. Where I am currently at is defining buttonColor
as a state which changes on the click of the button; the initial color should be #FD8F83
and the final color after the click should be #A4D87C
. However, I am currently getting the error “TypeError: Cannot read property ‘state’ of undefined” pointing to the style={{backgroundColor: this.state.buttonColor}}
line whenever the code is compiled on the webpage.
Defining initial state and behavior on click:
getInitialState: function() {
return {
buttonColor: "#FD8F83"
};
},
handleClick(color) {
this.setState({
buttonColor: color
});
}
Code inside table in render():
<td>
<button
className="removeButton"
style={{backgroundColor: this.state.buttonColor}}
onClick={function(){this.handleClick("#A4D87C")}}>
Yes
</button>
</td>
Does anyone have any ideas why this is? I am brand new to React so I apologize if it’s obvious. I also learned React using createClass so I’ve been trying to piece together how to make this work with the new create-react-class
package. Any advice is greatly appreciated!
React: ^16.2.0
Chrome: Version 63.0.3239.132 (Official Build) (64-bit)
Issue Analytics
- State:
- Created 6 years ago
- Comments:10 (4 by maintainers)
@dallashuggins replace
this.props.customers.map(function(customer, index) {
with
this.props.customers.map((customer, index) => {
and that should fix it. The
function
keyword switches the context ofthis
to be whatever object the function is bound to, in this case it’s undefined. Arrow functions were added to JavaScript because of this behavior since they do not change the context ofthis
.Also for future reference this is an issue thats better for some place like Stack Overflow, these threads are for tracking bugs.
The problem is:
In JS
this
does not get preserved this way.If you want to keep
this
value from the render method you can use an arrow function:Hope this helps!