Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks dynamic input

I've got a form component, where you can add an input on click of the button, creating a new team, where you can add players for.

The problem is, that if you fill in a value, all inputs will be filled with that value, because it is using the same state. My guess is to make a new state value for each new team (something like 'input' + index, which would result in states like input0, input1, input2, etc).

Though I can't implement this using React Hooks as you have to declare your state at first, and assign a set function to it.

Any thought on how I can implement this behaviour?

like image 494
Jur Avatar asked Mar 05 '23 07:03

Jur


1 Answers

Here's just one solution that's pretty straightforward, keeping track of values in an array, just to illustrate that hooks don't make anything more difficult:

function App() {
  let [inputs, setInputs] = useState([""]);

  return (
    <div className="App">
      <button onClick={() => setInputs(inputs.concat(""))}>Add input</button>
      <form>
        {inputs.map((value, i) => (
          <div key={i}>
            <label>Input {i + 1}</label>
            <input
              value={value}
              onChange={e =>
                setInputs(
                  inputs.map((value, j) => {
                    if (i === j) value = e.target.value;
                    return value;
                  })
                )
              }
            />
          </div>
        ))}
      </form>
    </div>
  );
}

codesandbox

like image 164
azium Avatar answered Mar 18 '23 05:03

azium