Steve
Steve

Reputation: 395

Why is react text input not changing when useState array element changes?

function Example() {
    const [strings, setStrings] = useState(["hi","yo"]);

    return (
      <div>
         <input name='foo' type="text" value={strings[0]}  onChange={setElement} />
      </div>
    );

    function setElement(e){
        let copyStrings = strings; 
        copyStrings[0] = e.target.value; 
        setStrings(copyStrings)
    }
 }

When I type a key in the text input box, I can see in react devtools that the state for the useState hook is updated to include that key, but the text displayed in the input doesn't change. Why is this and how do I fix it?
I have an array of values that I want the user to be able to edit in input controls.

Upvotes: 1

Views: 2220

Answers (1)

Tomer Almog
Tomer Almog

Reputation: 3868

let copyStrings = strings is a shallow copy. You are copying the reference to the array

you need to do a deep copy. There are a few options:

let copyStrings = [...strings]; //works with arrays or let copyStirngs = JSON.parse(JSON.stringify(strings)); // works with objects as well

Upvotes: 2

Related Questions