skip to Main Content

I thought I can allocate useRef to a React.js component and then have access to the functions in it.
I knew the old way handling refs in class components.

There I was able to do something like this:

class MyParentComponent extends Component {
...
    render() {
         return (
             <MyComponent
                 ref="myRef"
             />
         )
    }

Within this MyComponent there is a function called focus which focus the first DOM element within MyComponent component.

class MyComponent extends Component {
   ...
   focus() {
      ... //focus first DOM element in component
   }
}

That worked fine. I could i.e. do this:

class MyParentComponent extends Component {
...
    componentDidUpdate(prevProps, prevState) {
        this.refs["myRef"].focus();
    }
}

This called the function focus within the component MyComponent – so the first DOM element has got focus.

Now with useRef it seems to be more complicated when want to use the focus function of MyComponent.
Actually the code looks like this:

function MyParentComponent(props) {
   ...
   const myRef = useRef(null);
   ...
   return (
       <MyComponent
           ref={myRef}
       />
   )
}

But when I want to use this as before, this does not work:

useEffect(() => {
    myRef.current.focus();
},[someStateVariableChanged]);

How can I achieve this functionality?

2

Answers


  1. you should add ref as a dep in useEffect and check if the ref is valid and use myRef.current:

    useEffect(() => {
        if(myRef.current)
            myRef.current.focus();
    }, [someStateVariableChanged, myRef]);
    
    Login or Signup to reply.
  2. You need to pass the ref to a built-in component (like div), not a custom component. If you want to pass a ref to a custom component you need to use forwardRef. See https://react.dev/learn/manipulating-the-dom-with-refs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search