How would you create a custom input component using useImperativeHandle?
Let say you want to create an CustomInput
Component
Which expose focus
and clear
function to it's parent.
import React, { useRef, useImperativeHandle, forwardRef } from "react";
const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(
ref,
() => ({
focus: () => {
inputRef.current.focus();
},
clear: () => {
inputRef.current.value = "";
},
}),
[] // No dependencies, as nothing dynamic is involved
);
return <input ref={inputRef} {...props} />;
});
function App() {
const inputRef = useRef();
return (
<div>
<CustomInput ref={inputRef} placeholder="Type something..." />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
<button onClick={() => inputRef.current.clear()}>Clear Input</button>
</div>
);
}
export default App;