Alex D. Alex D. - 1 year ago 178
React JSX Question

React how to append new element to state?

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

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
but it's giving me
Uncaught TypeError: is not a function
that's probably it returns length of an array not itself.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download