Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus on custom input in ReactJS using useRef and react hooks?

I am using custom input element and want to set focus on it after initial render. Here is my custom input element: (simple though)

import React from 'react';
import './Input.scss';

const input = (props) => (
    <input 
        type={props.inputtype} 
        className="input" 
        placeholder={props.hint}
        style={{width: props.width}} {...props}/>
);

export default input;

And this is how I am using it in my functional component:

const SignupPopup = (props) => {

const inputEmailRef = useRef(null);
//...
useEffect(() => {
    inputEmailRef.current.focus();
}, []);

return ( 
   <Input
      inputtype="email"
      hint="Email"
      width="100%"
      id="inputemail"
      ref={inputEmailRef}
      value={email}
      required
      onBlur={emailBlurHandler}
      onChange={inputChangeHandler}
      />);
}

Error:

TypeError: Cannot read property 'focus' of null

enter image description here

All examples and codes that I have seen work only on native <input ref={myRef} /> element but is there any way to do it in custom input element or wrapped input element?

like image 504
Faizan Mubasher Avatar asked Aug 31 '25 21:08

Faizan Mubasher


1 Answers

You should use React.forwardRef to pass a ref to native input in your custom component:

import React from 'react';
import './Input.scss';

const input = React.forwardRef((props, ref) => (
    <input 
        type={props.inputtype} 
        className="input" 
        placeholder={props.hint}
        style={{width: props.width}}
        ref={ref}
        {...props}
    />
));

export default input;

More details:- https://en.reactjs.org/docs/forwarding-refs.html

like image 146
Alexandr Avatar answered Sep 03 '25 10:09

Alexandr