React.js - useRef used in React component instead of DOM object

47 Views Asked by At

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

There are 2 best solutions below

0
Amir Hossein On

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]);
0
Anna On

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