motleydev motleydev - 2 months ago 8
React JSX Question

Replace object in array on react state

This question might fall a little on the side of a "best practice" question, but please bear with me.

Here is a portion of my state:

this.state = {
typeElements: {
headers: [
{
name: "h1",
size: 70,
lineHeight: 1.25,
kearning: 0,
marginAfter: 0
}, {
name: "h2",
size: 70,
lineHeight: 1.25,
kearning: 0,
marginAfter: 0
}, {
name: "h3",
size: 70,
lineHeight: 1.25,
kearning: 0,
marginAfter: 0
}...


What I need to do is REPLACE the object at a given index on the headers array.

I don't know how to do that with the setState method as in
this.setState(headers[1] = {obj})
- but that's obviously invalid. My current method is creating a new array and clobbering the old one like this:

_updateStyle(props) {
let newState = Object.assign({}, this.state)
newState.typeElements.headers[props.index] = props
this.setState(newState)
};


For my small hacky project I guess it's OK but I feel like this is super heavy handed and would quickly lead to performance issues at any kind of scale.

Answer

React has some immutability helpers for this, which is explained in the docs: https://facebook.github.io/react/docs/update.html

In your case you could use the $splice command to remove one item and add the new one at given index, for example:

_updateStyle (props) {
  this.setState(update(this.state.typeElements, 
    { $splice: [[props.index, 1, props]] }
  ));
}