Reputation: 85
I am making a React app in which I play with creating, removing and editing components (more exactly changing their text). I have a basic Component, called 'MyComponent', and a 'Board' component, which contains all the 'MyComponent's created in an array called 'components', which is a state in the 'Board'. Removing and adding a new component works perfectly.
The idea behind editing is that when the user clicks the "Edit" button, the state "Editing" changes to true, and a textarea is displayed so the user can type the new text, and when he wants to click save, the "Editing" state goes back to false, thus going back to the view of a div with the name. (the name should also be updated).
Error name: Uncaught TypeError: Cannot read property 'components' of undefined.
Link to the code: https://github.com/AndreiEneCristian/ReactComponents/blob/master/EventHandl2.html
For a reason I do not know, whenever I try to save an edited component, thus changing its text and going back to the renderNormal function in "MyComponent", the browser gives me the error "Cannot read property 'components' (which is a state) of undefined". I tried to print some lines in the console, for debugging reasons, the data is correctly handled (meaning the state of 'MyComponent' successfully changes to false, the newText is saved in the "newText" variable) but it crashes because "this.state" is undefined.
The console error points me to this line: "var arr = this.state.components;" in the function:
updateComponent: function(newText, i) {
console.log(this.state);
var arr = this.state.components;
arr[i] = newText;
this.setState({components: arr});
},
Note: this.state is undefined, which is the issue behind it all. How can I solve this?
Upvotes: 0
Views: 1806
Reputation: 20775
You have to bind the function you are passing as prop
<MyComponent key={i} index={i} updateComponentText={this.updateComponent.bind(this)} deleteFromBoard={this.removeComponent}>
{text}
</MyComponent>);
Upvotes: 3