Home > Net >  save values of arrays inside a state from different input fields
save values of arrays inside a state from different input fields

Time:05-08

i want to get the values from 5 input fields and save them inside a single state of arrays , how can i achieve that ?

const [features,setFeatures] = useState([]);

const handleChange = e => {
    setFeatures(prev => ({ ...prev, features, [e.target.name]: e.target.value }))
}

<Input type="text" name="features" label="Feature 1" value={features} required change={handleChange} />
<Input type="text" name="features" label="Feature 2" value={features} required change={handleChange} />
<Input type="text" name="features" label="Feature 3" value={features} required change={handleChange} />
<Input type="text" name="features" label="Feature 4" value={features} required change={handleChange} />
<Input type="text" name="features" label="Feature 5" value={features} required change={handleChange} />

CodePudding user response:

You can check the below implementation

Note that I hardcoded the array length and I'd assume your input array is static. If your input array is dynamic, you can use iteration for generating input fields. Besides that, I modified Input to input and change to onChange for the primitive input element. The button and form are for demo only.

const App = () => {
   const [features,setFeatures] = React.useState(new Array(5));

   const handleChange = (e,index) => {
      const updatedFeatures = [...features] //clone data
      updatedFeatures[index] = e.target.value
      setFeatures(updatedFeatures)
   }
   
   const handleSubmit = (e) => {
      e.preventDefault();
      console.log(features);
   }

   return (<form onSubmit={handleSubmit}><input type="text" name="features" label="Feature 1" value={features[0]} required onChange={(e) => handleChange(e, 0)} />
<input type="text" name="features" label="Feature 2" value={features[1]} required onChange={(e) => handleChange(e, 1)} />
<input type="text" name="features" label="Feature 3" value={features[2]} required onChange={(e) => handleChange(e, 2)} />
<input type="text" name="features" label="Feature 4" value={features[3]} required onChange={(e) => handleChange(e, 3)} />
<input type="text" name="features" label="Feature 5" value={features[4]} required onChange={(e) => handleChange(e, 4)} />
<button type="submit">Submit</button>
</form>)
}

ReactDOM.render(
  <App/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

  • Related