Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

DOM remove method in react js

I want to change remove a certain tag with an id in the html page, eg.<div id="theid"><p>sometext</p></div>
Is there any ways to do it with react js? I know I can do it with javascript by document.getElementById("theid").remove();, how can I do it in the react way? I don’t need a button or anything, just simply remove it when the page loads. I’d prefer methods without importing any modules or libraries if possible. Thank you.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should likely use a ref:

https://reactjs.org/docs/refs-and-the-dom.html

So you attach the ref to the DOM element, then you can imperatively remove that element just like you specified.

So in the component function body:

const myRef = useRef();

Then in the component render:

<Component ref={myRef} />

Then you can use the code in your question to remove the element from the DOM.

ref.remove();

If you need to do it when the page loads look at using useEffect to achieve this. Although if you’re removing an element on page load, I question why you even need the element there in the first place ;).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading