Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update multiple object children fields using the ES6 spread?

We have the options for react-graph-vis in state:

{
    options: {
        physics: {
            enabled: false
            ...
        }
    }
    nodes: {
        font: “12px sans-serif #888f99”
        ...
    }
}

We want to update options.physics.enabled and options.nodes.font with props from the parent component without removing or editing any other default options in state:

<Graph
    graph={this.state.graph}
    options={{
        ...this.state.options,
        physics: { enabled: {this.props.isPhysicsOn}},
        nodes: {nodes: {font: this.props.isNodeLabelShowing ? ‘12px sans-serif #888f99’ : ‘12px sans-serif transparent’},
    }}
    events={this.events}
/>

Am I holding it wrong?

like image 475
William Donnell Avatar asked Aug 16 '18 19:08

William Donnell


1 Answers

Your first spread is great, you just need to spread for the children objects too.

<Graph
  graph={this.state.graph}
  options={{
    ...this.state.options,
    physics: {
      ...this.state.options.physics,
      enabled: this.props.isPhysicsOn
    },
    nodes: {
      ...this.state.options.nodes,
      font: this.props.isNodeLabelShowing ? '12px sans-serif #888f99' : '12px sans-serif transparent',
    },
  }}
  events={this.events}
/>

You’re correct in that you are removing all other fields in physics and nodes. Try this ^^ out.

like image 178
Brantley English Avatar answered Nov 09 '22 13:11

Brantley English