Home > Net >  how to add component on button click in react
how to add component on button click in react

Time:09-30

Hello I want to add a react component to the dom on button click. Here I have a simple function for it.

const addCargo = () => {
        const parentElement = document.getElementById("addCargoContainer");
        parentElement.insertBefore(<Cargo />, parentElement.children[2]);
    }

but this gives me the following error:

Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': parameter 1 is not of type 'Node'.

Is there a possible way to do this?

CodePudding user response:

Will something like this work?

function Cargo() {
  return <div>cargo</div>
}

function Ship() {
  const [cargos, setCargos] = useState([])

  const handleAddCargo = () => {
    const newCargo = Date.now()
    setCargos(v => [...v, newCargo])
  }

  return (
    <>
      <h1>ship</h1>
      <button onClick={handleAddCargo}>add cargo</button>
      {cargos.map(() => <Cargo />)}
    </>
  )
}

  • Related