DEV Community

Cover image for React - TypeError: this.state.<arr>.map is not a function when using map to render an element
Ben Morris
Ben Morris

Posted on

React - TypeError: this.state.<arr>.map is not a function when using map to render an element

tl:dr Check the function in your constructor that implements the adding of an item to an array, references the array it is adding to as prepending, rather than appending, the method.

In short, does your code look like this:

submitMessage() {
  this.setState({
    messages: this.state.input.concat(this.state.messages),
    input: ''
  })

Instead of the correct:

submitMessage() {
  this.setState({
    messages: this.state.messages.concat(this.state.input),
    input: ''
  })

Don't be me, array first, item second....

The purpose of this post was to bore the correct usage of Array.prototype.concat() & Array.prototype.push() in to my porous mind, whilst simultaneously, hopefully, helping another Array-method-challenged soul avoid some futile debugging time on their react app.

Having spent too long debugging this same issue twice now, it felt right to write a quick post to stop others from potentially doing the same.

Better yet ??..... Avoid the above possibility of getting the order wrong altogether and use the ES6 spread operator instead:

submitMessage() {
  this.setState({
    messages: [...this.state.messages, this.state.input]
    input: ''
  })

✌️

Discussion (0)