1

I am trying to figure how to update an array state and output the changes in input for my React Js Project.

I am trying to display multiple input components on the screen by mapping an array with the input component as it's child. I want to change the value of individual item with onChange()function and want to view the changes inside the input component.

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [array, setArray] = useState(["1", "2", "3"]);
  return (
    <div className="App">
      {array.map((item, index) => (
        <input
          type="text"
          value={array[index]}
          onInput={(e) => {
            setArray((array) => {
              array[index] = e.target.value;
              return array;
            });
          }}
        />
      ))}
    </div>
  );
}

The Updates are not being displayed.

0

1 Answer 1

3

This should work :

<input
  key={index}
  type="text"
  value={array[index]}
  onInput={(e) => {
    setArray((prevArr) => {
      const result = [...prevArr];
      result[index] = e.target.value;
      return result;
    });
  }}
/>
Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou Shadi... Can you explain how this worked.
You are using the same variable name in defining state and below in setting state (both are array which cause issues). By defining a new array contains the prevState items we ensure that we have a copy of current state (array) and after manipulating it and returning the value then setState will do what's expected to do.

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.