2

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?

2
  • 2
    You probably want to be setting state instead. Commented Sep 30, 2022 at 14:50
  • const {cargos, setCargos} = useState([<Cargo />]) const addCargo = () => { setCargos([...cargos, <Cargo />]) } Well I tried this but doesnt seem to be working too Commented Sep 30, 2022 at 14:59

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.