Home > database >  Create an array from two input fields in React
Create an array from two input fields in React

Time:11-27

Newbie React Question. Assuming the following inputs

          <div className="col-md-6">
            <input
              className="form-control"
              name="manufacturer"
              type="text"
              onChange={handleReferencesChange}
              value={references}
            />
          </div>

          <div className="col-md-6">
            <input
              className="form-control"
              name="vehicleNumber"
              type="text"
              onChange={handleReferencesChange}
              value={references}
            />
          </div>

I wrote the function handleReferencesChange to grab the values of both inputs inside an array (references) which will then be pushed into the database (mongoDB)

  const handleReferencesChange = (e) => {
    e.preventDefault();
    setValues({ ...values, references: [], [e.target.name]: e.target.value });
  }

Unfortunately I can not can not populate the references array (which I already initialized as and empty array)

Please can you help me understand why the values are not stored in the array but instead created as separated values. See screenshot below.

JSON.stringify Screeshot

CodePudding user response:

Your setValues code says, "take all the values, add an empty references array to it, then add/overwrite the field name of the input with the value from the event".

If you want to push stuff into an array, you need to use push. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

const handleReferencesChange = (e) => {
    e.preventDefault();
    const newReferences = values.references.push({[e.target.name]: e.target.value})
    const newValues = {...values, references: newReferences}
    setValues(newValues);
  }
  • Related