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

237
Visualizações
React Hooks - Using useRef without direct access to HTML Element Code?

With React I'm inside of one repository, and the HTML elements are loading from another repo, which I watch for using pageLoaded. Inside updateHeader there is just more HTML element selecting and attribute/class manipulation.

useEffect(() => {
        if (pageLoaded.status) {
            if (someCondition) {
                updateHeader(ubeName);
            } else {
                document.querySelector('.headerbar-menu').style.display = 'block';
                if (document.querySelector('.headerbar-menu.affiliates-wrapper')) {
                    document.querySelector('.headerbar-menu.affiliates-wrapper').style.display = 'none';
                }
            }
        }
    }, [pageLoaded.status])

The problem here is obviously we shouldn't be using querySelector, and i think it may be causing some unexpected functionality. The elements dont properly evaluate and render until some piece of state changes i.e. a scroll state handler, so on initial page load the elements dont show with their new attributes until a scroll.

I'd like to attempt to resolve using useRef, but don't have direct access to the html. Is there a way to dynamically connect a ref to an element without access to the HTML code?

Thanks for your time and attention!

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

0

The best way to do this, in my opinion, is in this sequence:

  1. Attempt to select the element
  2. If non-existant, set up a DOMSubtreeModified event handler or a MutationObserver
  3. Clean up DOMSubtreeModified event handler or a MutationObserver (or keep it around to watch for updates)

This allows for use of query selectors in a safe and modern way which doesn't stray too far from React's recommendations

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