1

I want to add new input tags to my web page when I click on Add input button.

Attempt:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [addInput, setAddInput] = useState(false);
  const handleClick = () => setAddInput(true);
  return (
    <div className="App">
      <button onClick={handleClick}>Add Input</button>
      {addInput ? <input type="text" /> : ""}
    </div>
  );
}

How can I make the above code work to dynamically add new inputs?

2
  • So if I understand this correctly, you want to add several input tags and not only one? Commented Oct 7, 2020 at 9:07
  • @khenriksson yes. that's correct. Thanks for your comment Commented Oct 7, 2020 at 9:08

1 Answer 1

1

One way to do want you want.

const [state, setState] = useState([]);

const handleClick = () => {
    let inputs = Object.assign([], state);
    inputs.push(<input type='text' key={inputs.length} />);

    setState(inputs);
}

return (
    <div className="App">
        <button onClick={handleClick}>Add Input</button>
        {state}
    </div>
);

You should know, added inputs are Uncontrolled Components.

In order to help you to learn more about the possible solutions, here is another approach:

const [state, setState] = useState(0);

const handleClick = () => setState(state + 1);

const generateInputs = () => {
    const inputs = [];

    for (let i = 0; i < state; i++) inputs.push(<input key={i} type='text' />);

    return inputs;
}

return (
    <div className="App">
        <button onClick={handleClick}>Add Input</button>
        {generateInputs()}
    </div>
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the additional solution and more info on Uncontrolled components. It is helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.