Reputation: 471
I am new to reactjs and trying to learn the concepts. I am creating demo sticky notes app on reactjs. I am getting error
index.js: Uncaught TypeError: Cannot read property 'notes' of undefined
I have Board component and Notes components as follows.
Notes Component:
import React from 'react';
import ReactDOM from 'react-dom';
class Note extends React.Component {
constructor() {
super();
this.state = {editing: false}
this.edit = this.edit.bind(this);
this.save = this.save.bind(this);
}
edit() {
this.setState({editing: true});
}
save() {
this.props.onChange(ReactDOM.findDOMNode(this).value, this.props.index);
this.setState({editing: false});
}
remove() {
this.props.onRemove(this.props.index);
}
renderDisplay() {
return (
<div className='note'>
<p>{this.props.children}</p>
<span>
<button onClick={this.edit} className='btn btn-primary glyphicon glyphicon-pencil'/>
<button onClick={this.remove} className='btn btn-danger glyphicon glyphicon-trash'/>
</span>
</div>
);
}
renderForm() {
return (
<div className='note'>
<textarea className='form-control' defaultValue={this.props.children} ref='newText'></textarea>
<button className='btn btn-success btn-sm glyphicon glyphicon-floppy-disk' onClick={this.save} />
</div>
);
}
render() {
if(this.state.editing) {
return this.renderForm();
} else {
return this.renderDisplay();
}
}
}
export default Note;
And Board Component:
import React from 'react';
import ReactDOM from 'react-dom';
import Note from './Note';
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
notes: [
'Check emails',
'Log in to jira',
'Fix the issues',
'Logout the system'
]
}
}
update(newText, i) {
console.log(this);
console.log(this.state);
var arr = this.state.notes;
arr[i] = newText;
this.setState({notes: arr});
}
remove(i) {
var arr = this.state.notes;
arr.splice(i, 1);
this.setState({notes: arr});
}
eachNote(note, i) {
return (
<Note key={i}
index={i}
onChange={this.update}
onRemove={this.remove}
>{note}</Note>
);
}
render() {
return (
<div className='board'>
{this.state.notes.map(this.eachNote, this)}
</div>
);
}
}
ReactDOM.render(<Board></Board>, document.getElementById('react-container'));
export default Board;
I am getting error when i try to update a note, as the note is render using the state notes variable and i have attached a property on each note as onChange: {this.update}. In update i am accessing state variable notes but state is undefined.
Can anyone give me suggestions about it. Thanks
Upvotes: 0
Views: 304
Reputation: 1895
For better performance, React recommends binding event handlers in the constructor so they are only bound once for every instance. Read more here: https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
Upvotes: 0
Reputation: 74176
Try:
onChange={this.update.bind(this)}
Instead of:
onChange={this.update}
Upvotes: 1