Bot Ellis
Bot Ellis

Reputation: 128

how to add component on button click in react

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?

Upvotes: 2

Views: 3122

Answers (2)

Vipin rao
Vipin rao

Reputation: 9

const [isCargoVisible,setIsCargoVisible] = useState(false);
return(
    <>
    <button onClick={()=>setIsCargoVisible(true)}>Hit me to add cargo div</button>
    {
      isCargoVisible ? (
        <div id='addCargoContainer'>
          {/* Your code inside */}
        </div>
       ) : null
    }
  </>
)

Upvotes: 1

twharmon
twharmon

Reputation: 4272

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 />)}
    </>
  )
}

Upvotes: 4

Related Questions