ReactJs How to update state of specific object nested in an array reactjs update state,reactjs update array in state,reactjs update

I have an array of objects. I want my function clicked() to add a new parameter to my object (visible: false). I'm not sure how to tell react to update my state for a specific key without re-creating the entire array of objects.

First of all, is there an efficient way to do this (i.e using the spread operator)?

And second of all, perhaps my entire structure is off. I just want to click my element, then have it receive a prop indicating that it should no longer be visible. Can someone please suggest an alternative approach, if needed?

import React, { Component } from 'react';
import { DefaultButton, CompoundButton } from 'office-ui-fabric-react/lib/Button';
import { Icon } from 'office-ui-fabric-react/lib/Icon';
import OilSite from './components/oilsite';
import './index.css';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      mySites: [
        {
          text: "Oil Site 1",
          secondaryText:"Fracking",
          key: 3
        },
        {
          text: "Oil Site 2",
          secondaryText:"Fracking",
          key: 88
        },
        {
          text: "Oil Site 3",
          secondaryText:"Fracking",
          key: 12
        },
        {
          text: "Oil Site 4",
          secondaryText:"Fracking",
          key: 9
        }
      ],
    }
  };

  clicked = (key) => {
    // HOW DO I DO THIS?
  }

  render = () => (
    <div className="wraper">
      <div className="oilsites">
          {this.state.mySites.map((x)=>(
            <OilSite {...x} onClick={()=>this.clicked(x.key)}/>
          ))}
      </div>
    </div>
  )
};

export default App;
Answer:1

You can use the index of the array to do a O(1) (No iteration needed) lookup, get the site from the array, add the property to the object, update the array and then set the state with the array. Remeber, map has 3 parameters that can be used (value, index, array).

UPDATE: Fixed Some Typos

class Site
{
  constructor(text, scdText, key, visible=true)
  {
    this.text = text;
    this.secondaryText = scdText;
    this.key = key;
    this.isVisible = visible;
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      mySites: [
        new Site("Oil Site 1", "Fracking", 3),
        new Site("Oil Site 2", "Fracking", 88),
        new Site("Oil Site 3", "Fracking", 12),
        new Site("Oil Site 4", "Fracking", 9)
      ],
    }
    this.clicked = this.clicked.bind(this);
  };
  //Change to a normal function
  clicked(ind)
  {
  //Get the sites from state
    let stateCopy = {...this.state}
    let {mySites} = stateCopy;
    let oilSite = mySites[ind]; //Get site by index
    //Add property to site
    oilSite.isVisible = false;
    mySites[ind] = oilSite;//update array
    //Update the state
    this.setState(stateCopy);

  }

  render = () => (
    <div className="wraper">
      <div className="oilsites">
        {this.state.mySites.map((site, ind) => (
          //Add another parameter to map, index
          <OilSite {...site} onClick={() => this.clicked(ind)} />
        ))}
      </div>
    </div>
  )
};
Answer:2

Like this:

clicked = (key) => {
    this.state(prevState => {
      // find index of element
      const indexOfElement = prevState.mySites.findIndex(s => s.key === key);
      if(indexOfElement > -1) {
        // if element exists copy the array...
        const sitesCopy = [...prevState.mySites];
        // ...and update the object
        sitesCopy[indexOfElement].visible = false;
        return { mySites: sitesCopy }
      } 
      // there was no element with a given key so we don't update anything
    })
}
Answer:3



  1. reactjs update state
  2. reactjs update array in state
  3. reactjs update props
  4. reactjs update component
  5. reactjs update url without reload
  6. reactjs update child state from parent
  7. reactjs update state when props change
  8. reactjs update object in array

I have an app where I have a horizontal list of items, that when you click them they should disappear and trigger some action. Minimal demonstration here: Code: https://codesandbox.io/s/5xpkn3nzxl ...

I have an app where I have a horizontal list of items, that when you click them they should disappear and trigger some action. Minimal demonstration here: Code: https://codesandbox.io/s/5xpkn3nzxl ...

Following are my configs: Package.json: "dependencies": { "axios": "^0.18.0", "babel-preset-env": "^1.7.0", "extract-text-webpack-plugin": "^4.0.0-beta.0", "node-sass": "^4.7.2", ...

Following are my configs: Package.json: "dependencies": { "axios": "^0.18.0", "babel-preset-env": "^1.7.0", "extract-text-webpack-plugin": "^4.0.0-beta.0", "node-sass": "^4.7.2", ...