Alex D. Alex D. - 11 days ago 6
React JSX Question

React how to append new element to state?

I'd like to append new element to my products state, currently using

.concat
but it's adding to the end of an array, but I need to add to the beginning.

var Body = React.createClass({
getInitialState() {
return { products: [] }
},

handleSubmit(product) {
var newState = this.state.products.concat(product);

this.setState({ products: newState });
},
});


Tried to used
this.state.products.unshift(product)
but it's giving me
Uncaught TypeError: this.state.tickets.unshift is not a function
that's probably it returns length of an array not itself.

Answer

Just change the order of your concatenation. If "product" is a single item and not an array, then do this:

var newState = [product].concat(this.state.products);

if "product" is already an array, just this:

var newState = product.concat(this.state.products);