0

I have an array of [false,true,false,false,true] I want to change these boolean values based on index number . I tried my best but didn't find a solution to resolve this issue. I want to be done this in react .

    this.setState({
       stateValue:[...array,array[0]=true]
   })

I tried with this solution but it can add value at the end of array

6
  • why don't you array[index] = true and call setState? Commented Nov 6, 2020 at 20:37
  • What is the rule for change? Commented Nov 6, 2020 at 20:37
  • Does this answer your question? How do I modify the value of an array of Bool in React? Commented Nov 6, 2020 at 20:39
  • You can do this with array map(). Before learning react it is recommended that you have a solid understanding of advanced array methods such as map, filter, reduce & other ES6+ features. Commented Nov 6, 2020 at 20:40
  • 1
    can you provide a more complete version of your code? please see How to create a Minimal, Reproducible Example Commented Nov 6, 2020 at 21:09

2 Answers 2

0

I would do something like:

this.setState(prevState => {
  const newStateValue = [...prevState.stateValue]
  newStateValue[desired_index] = boolean_value
  return {
    ...prevState,
    stateValue: newStateValue,
  }
})

it's good practice when modifying state to do so in an immutable way, by first copying the data, manipulating the new copy and then setting that back into state.

using the prevState => {} callback to setState also helps to ensure the state changes get applied in the correct order if they occur in quick succession

Sign up to request clarification or add additional context in comments.

3 Comments

actually, it not updating state
it's just sample code, obviously some of the variables are undefined / don't match up exactly how you would use it as just a drop in... did you change out the values with what you were trying to do?
Yes, I changed values but state is not updating actually
-1

Or this...

     var newArray = this.state.statevalue;
     newArray[i] = true;
     this.setState({stateValue: newArray});

1 Comment

This will also modify the current this.state.stateValue value... thats a bad practice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.