Lizz Parody
Lizz Parody

Reputation: 1765

How to replace the value of an array of objects in React

I have this function that returns an array of objects, every object represent a sticky, what I want is to change the value of "content" everytime I click one of the stickies

  handleStickyEdition = (index) => {
    const { currentStage } = this.props
    const stickies = currentStage.get('stickies')
    const updatedStickies = [...stickies]
    console.log(updatedStickies)
  }

And the result of calling the console.log is this array of objects: enter image description here

If I do console.log(updatedStickies[index].get('content')) I will get the content of the object I want to change. For example name 3.

How can I replace this content with an empty string? in other words, if I click the object in the position 0, how can I make name 3 equals to ''

Upvotes: 1

Views: 762

Answers (1)

Francis Malloch
Francis Malloch

Reputation: 1094

I would suggest using a map like so.

this.setState({
  updatedStickies: this.state.updatedStickes.map(sticky => ({
    ...sticky
    content: sticky.id === idOfStickyWeWantToUpdate ? "" : "content"
  }))
});

I see you are reading stickies from props, I would suggest having a function in your parent component to run the above code which you can call from your child component if need be.

Upvotes: 1

Related Questions