Iggy Iggy -4 years ago 398
React JSX Question

ReactJS Uncaught TypeError: Cannot read property 'concat' of undefined

I want to add an element into state everytime a Submit button is pressed. The problem is, everytime I press the submit button, it return

Uncaught TypeError: Cannot read property 'concat' of undefined
error and I could not figure out why it is undefined.

class ChatRoom extends React.Component{
constructor(props){
super(props);
this.state = {
rooms: ['room1', 'room2'],
chatRoom: ''
}
}

handleAddRoom = (e) => {
console.log('handleAddRoom', e);
this.setState({
rooms: this.state.notes.concat(e)
})
}
handleSubmit(){
var newRoom = ReactDOM.findDOMNode(this.refs.room).value;
console.log(newRoom);
ReactDOM.findDOMNode(this.refs.room).value = '';
this.handleAddRoom(newRoom);
}
render(){
console.log("rooms: ", this.state.rooms)
return(
<div>
Hello from chat room!! Please enter new room:

<input type="text" className="form-control" placeholder="Add a new note" ref="room" />
<span className="input-group-btn">
<button className="btn btn-default" type="button" onClick={this.handleSubmit.bind(this)}>Submit</button>
</span>
</div>
)
}
}


This is the component that is giving me problem. I put
console log
on various locations and they are all returning the right values. Somehow when it is trying to concat JS says it is
undefined
value. How can I concat the element into
rooms
state?

Answer Source

this line:

rooms: this.state.notes.concat(e)

You haven't defined notes anywhere and it is therefore saying that it can't do a concat on undefined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download