Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  160] [ 3]  / answers: 1 / hits: 11978  / 4 Years ago, fri, october 23, 2020, 12:00:00

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


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?


More From » reactjs

 Answers
3

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


[#2435] Monday, October 19, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janjadonb

Total Points: 4
Total Questions: 114
Total Answers: 118

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
janjadonb questions
Tue, Nov 10, 20, 00:00, 4 Years ago
Wed, Oct 14, 20, 00:00, 4 Years ago
Tue, Apr 14, 20, 00:00, 4 Years ago
Thu, Mar 19, 20, 00:00, 4 Years ago
;