Home > Mobile >  Cannot read properties of undefined (reading 'focus')
Cannot read properties of undefined (reading 'focus')

Time:10-06

I am new to react and I have been trying to focus element but getting error:

Uncaught TypeError: Cannot read properties of undefined (reading 'focus')

import { useRef, useEffect } from 'react';

function CustomComponent() {
  const elementRef = useRef;
   useEffect(() => {
    const divElement = elementRef.current;
    divElement.focus();
  }, []);
  return (
    <div ref={elementRef}>
      I'm an element
    </div>
  );
}

Please help me how can I fix this.

CodePudding user response:

You should be invoking the method useRef() instead of just assigning it directly to variable elementRef. Try to change your code as follows and see if that helps:

import { useRef, useEffect } from 'react';

function CustomComponent() {
  const elementRef = useRef();
   useEffect(() => {
    const divElement = elementRef.current;
    divElement.focus();
  }, []);
  return (
    <div ref={elementRef}>
      I'm an element
    </div>
  );
}
  • Related