Home > Software engineering >  React focus div after it has loaded
React focus div after it has loaded

Time:09-26

I'm currently experimenting with React, and I've now run into an issue that I can't seem to solve.

In my application, I use a React library to handle hotkeys, these hotkeys have a scope, so when I want a certain set of hotkeys to be active in a div, I have to wrap that div with a <HotKeys> tag.

I have to toggle some of these divs, so I'll have something along the lines of

isActive ?
  <HotKeys ...>
    <div ...>...</div>
  </HotKeys>
  : <div ...>...</div>

I now need to figure out a way to focus the div when it's created. Pretty much every article on the web suggest something like this:

    const focusRef = useRef(null);
    useEffect(() => {
        focusRef.current.focus()
    })

    return (
        isActive ?
            <HotKeys ...>
                <div ref={focusRef} tabIndex={-1} ...>...</div>
            </HotKeys>
            : <div ...>...</div>
    )

I've tried some variations, including having the div top level (without the <HotKeys> wrapping them), all to no avail.

When I print the focusRef object in the useEffect method, I do get the expected output, focusRef is correctly set and current is populated, but calling the focus method doesn't work. At one point I tried calling the focus method from a button and manually triggering it after the component had fully loaded, it seemed to work (document.activeElement was being changed), then for some reason it stopped working again. All this leads me to believe that somehow the component hasn't fully loaded, despite calling the useEffect hook, which, if I understand correctly, triggers when the element has rendered for the first time/after every change to state.

I'd really appreciate some help with this, since I basically started learning React yesterday.

CodePudding user response:

I think I figured it out.

You were right about using the tabIndex but you needed to pass it in as a string like this:

tabIndex={"-1"}

When you first load it a dotted line box surrounds the div that has the ref attached. check out this code sandbox:

https://codesandbox.io/s/nifty-wildflower-eqjtk?file=/src/App.js

grabbed from this accepted answer where they pass in a string: Need to put focus on div in react

CodePudding user response:

You must to use an useCallback , because useRef don't notifies you when ref was created

https://reactjs.org/docs/hooks-reference.html#useref

  • Related