Home > database >  React js: How to Update A State (Of Array) From <input /> onChange method
React js: How to Update A State (Of Array) From <input /> onChange method

Time:08-17

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.

CodePudding user response:

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;
    });
  }}
/>
  • Related