Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda