0

I have two components for ex. <A/> and </B> and additionally <div id='test'>. After pressing the button ,,A1",i want insert the content of component <A/> into and after pressing the button ,,B1" i want insert the content of component into the <div id='test'> Very important: After pressing buttons the previous value in <div id='test'> must be deleted and replaced with the new value. How can i do it?

Best regards, Łukasz

I tried this, but the commands not delete previous value.

ReactDOM.createPortal(<A />, document.getElementById('test'));
ReactDOM.createPortal(<B />, document.getElementById('test'));


1 Answer 1

1

You create a true and false state for creating each of the portals. See below. I created two states and set them to false at the beginning:

const [mountedA, setMountedA] = useState(false);
const [mountedB, setMountedB] = useState(false);

When clicking on a button A1 or B1 you can run a function like below to set the desired state for each corresponding portal to show them or if the other one is visible, set its visibility to false:

const handleClickBtnA = () => {
  setMountedA(true);
  setMountedB(false);
}

const handleClickBtnB = () => {
  setMountedA(false);
  setMountedB(true);
};

And finally you could run this logic for returning each of the portals:

return mountedA
        ? ReactDOM.createPortal(<A />, document.getElementById("test"))
        : null;

return mountedB
        ? ReactDOM.createPortal(<B />, document.getElementById("test"))
        : null;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.