Search code examples
htmlreactjsappendchildcreateelement

How can I continuously append HTML element in JSX ? (React)



function sample () {

return (

<div>

<input/>
<input/>
<input/>
.
.
?

<button onClick={ ? ? ? ? }> ADD NEW INPUT <button>

</div>

)}

Let's pretend we're working on this code. Here, by clicking 'ADD NEW INPUT' button tag, I want to input tag to keep created.

I have looked for createElement() and appendChild(), but all I can do was only append just 1 HTML element to existing one.

I want to know how we can make a function or set up a logic to solve this kind of problem.


Solution

  •   const [input, setInput] = useState([<input defaultValue={1} />]);
      return (
        <div>
          {input.map((item, index) => (
            <div key={`input-${index}`}>{item}</div>
          ))}
          <button
            className="block p-5 mx-4 rounded-lg bg-emerald-600"
            onClick={() => {
              setInput([...input, <input defaultValue={input.length + 1} />]);
            }}
          >
            Append
          </button>
        </div>
      );