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

Time:04-10


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.

CodePudding user response:

You can check the below implementation

import React, { useState } from "react";

const Input = () => <input />; //input component

const Component = () => {
  const [inputs, setInputs] = useState([]); //create a state to keep all generated inputs

  return (
    <div>
      //re-render all inputs whenever we have a new input
      {inputs.map((Input, index) => (
        <Input key={index} />
      ))}
      //set a new input into the input list
      <button onClick={() => setInputs([...inputs, Input])}>Generate input</button>
    </div>
  );
};

export function App() {
  return <Component />;
};

Here is the playground

CodePudding user response:

  const [input, setInput] = useState([<input defaultValue={1} />]);
  return (
    <div>
      {input.map((item) => (
        <div>{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>
  );
  • Related