1
votes

I'm trying to gather the input data from a form dynamically rather than typing out each individual input field name. This was pretty easy using standard React, but I'm switching over to React Hooks and now I'm a bit confused on how to achieve the same goal.

const gatherFormData = e => {
  if (e.target.value !== null) {
    _.assign(
      formData.payload,
      { [e.target.name]: e.target.value, action },
      { groupNumber },
    );
    setState({ 
      [e.target.name]: (e.target.value),
      formData
    });
  }
};

I tried using template literal syntax, but that didn't work.

set`${e.target.name}`(e.target.value);
2
there is template literal syntax in hooks? maybe try and post a minimal example of your class and ask how to convert it to hooks.Dennis Vash
@DennisVash are you referring to the Standard React portion of my question?pingeyeg
When do you say Standard React do you mean react classes? I've never heard that expression before, using react hooks is a standard too.Dennis Vash
My bad, yes, React classes.pingeyeg
So like I mentioned above, post a minimal example of your class and ask how to convert it to hooks. Your question is unclear, what does "achieve the same goal."Dennis Vash

2 Answers

1
votes
import React, { useState } from "react";

function App() {
  const [inputList, setInputList] = useState([{ firstName: "", lastName: "" }]);

  return (
    <div className="App">
      <h3><a href="https://cluemediator.com">Clue Mediator</a></h3>
      {inputList.map((x, i) => {
        return (
          <div className="box">
            <input
              name="firstName"
              value={x.firstName}
            />
            <input
              className="ml10"
              name="lastName"
              value={x.lastName}
            />
            <div className="btn-box">
              {inputList.length !== 1 && <button className="mr10">Remove</button>}
              {inputList.length - 1 === i && <button>Add</button>}
            </div>
          </div>
        );
      })}
      <div style={{ marginTop: 20 }}>{JSON.stringify(inputList)}</div>
    </div>
  );
}

export default App;
0
votes

You can use useState with an object, making it so you can dynamically add stuff. Example:

const [targets, setTargets] = useState({});
// Set values like this
setTargets({...targets, [`${e.target.name}`]: e.target.value});

// Then get values:
const theValue = targets.yourTargetNameHere

When setting the value, you have to use spread syntax ({...targets) in order to maintain the other values you put in the object.