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

React focus useRef only working on refresh

I am using a <NavLink /> to direct navigation to a specific component. I am thinking this is the problem – but the problem is:

I am trying to have an element focused when the route is fulfilled and the component renders. The existing approach I have somewhat works – the scroll works (i.e., the element I want focused is near the bottom and the automatic scroll to works. However, the focus box is not there). When I refresh, however, it works as desired – the focus has the scroll to functionality and there is a highlighted box around the element.

I am not sure what the issue is but I am thinking it is the fact that component gets its initial render from the <NavLink />.

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

Here is how I am using the focus:

import React, { useEffect, useRef } from "react";

const Focus = () => {
  const focusRef = useRef(null);

  useEffect(() => {
    if (focusRef && focusRef.current) {
      focusRef.current.focus();
    }
  }, [focusRef.current]);

  return (
    <React.Fragment>
      <h1 tabIndex="-1" ref={focus}>
        Focus Here
      </h1>
    </React.Fragment>
  );
};

Any help is greatly appreciated!

>Solution :

The problem you are facing is that changing a ref does not trigger a render. You are using focusRef.current as a dependency of your useEffect hook, but in fact, when the current value of focusRef changes, it doesn’t necessarily trigger the effect, it simply mutates the ref only. So then you need something else to trigger the re-rendering and when that happens a change of the focusRef.current is detected and effect can re-run. And if focusRef.current never changes, the effect is only even trigger when the component mounts (this is why it works on refresh).

You are probably using the wrong tool to do the job. Ask yourself what you want to component to response to. Changing location? Then you need an effect to run based on location change, not a ref.

const focusRef = useRef()
const location = useLocation()

useEffect(() => {
  if (location.pathname === '/my-url') {
    focusRef.current.focus()
  }
}, [location])

Something like this triggers the effect on every change of location, then, inside the effect, you can put your condition for a pathname for example.

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