Home > Back-end >  DOM remove method in react js
DOM remove method in react js

Time:02-22

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.

CodePudding user response:

If it's rendered as part of React, the right way to do it would be to simply omit it from the source code:

const App = () => (
  <div>
    <div id="theid">foo</div>
    <div>more content</div>
  </div>
);

to

const App = () => (
  <div>
    <div>more content</div>
  </div>
);

If it's not part of React, then remove it from whatever process generates the HTML.

If that's not an option - if it must be part of the HTML served to the client and it's not rendered as part of React - then you'll have to resort to doing what you're currently doing:

document.getElementById("theid").remove();

probably completely separate from your React script, since it's something you want to do only once, when the page loads, and not something that needs to be a part of the React lifecycles.

CodePudding user response:

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 ;).

  • Related