Here is my code: I have created the input component and header component. if I comment on the useImperativeHandle hook, input focus is working fine. please check this code.
import { forwardRef, useImperativeHandle, useRef } from "react";
const Input = forwardRef((props, ref) => {
// here is useImperativeHandle
useImperativeHandle(ref, () => ({
// ```method```
someExposedProperty: () => {
alert("inside the exposed property function!");
}
}));
// Return statement
return (
<>
<input type="text" ref={ref} />
</>
);
});
// header component
export default function Header() {
const inputRef = useRef();
return (
<>
<div className="container">
<Input ref={inputRef} />
</div>
<button
// Click function.
onClick={() => {
inputRef.current.focus();
}}
>
Add focus
</button>
</>
);
}
CodePudding user response:
You need two refs here. One to bind the functions (which are going to expose to the outside) and another to keep a reference to the input element (this one is only used inside the Input
and not exposed to outside components).
Try like below:
import { forwardRef, useImperativeHandle, useRef } from "react";
const Input = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(
ref,
() => ({
focus: () => {
inputRef.current.focus();
}
}),
[]
);
return (
<>
<input type="text" ref={inputRef} />
</>
);
});
export default function Header() {
const inputRef = useRef();
return (
<>
<div className="container">
<Input ref={inputRef} />
</div>
<button
onClick={() => {
inputRef.current.focus();
}}
>
Add focus
</button>
</>
);
}
Working Demo