Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!