Skip to content

Instantly share code, notes, and snippets.

@huksley
Created July 26, 2022 09:09
Show Gist options
  • Save huksley/69c4c5aae89bc8fb149bf0e9caff1ac4 to your computer and use it in GitHub Desktop.
Save huksley/69c4c5aae89bc8fb149bf0e9caff1ac4 to your computer and use it in GitHub Desktop.
Example of passing data from child to parent using https://reactjs.org/docs/hooks-reference.html#useimperativehandle
import { createRoot } from "react-dom/client";
import React, {
forwardRef,
useImperativeHandle,
useRef,
useState
} from "react";
export type InputRef =
| {
focus: () => void;
register: (handler: Handler) => void;
}
| undefined;
type InputProps = {
children?: React.ReactNode | null;
selectedIndex?: number;
};
type Handler = (s: string) => void;
const Input = forwardRef<InputRef, InputProps>((_props: InputProps, ref) => {
const inputRef = useRef<HTMLInputElement>(null);
const [value, setValue] = useState("");
const [handler, setHandler] = useState<Handler | undefined>(undefined);
useImperativeHandle(
ref,
() => ({
focus() {
inputRef.current?.focus();
},
register(handler: Handler) {
setHandler(() => handler);
}
}),
[setHandler]
);
return (
<div>
<input
type="text"
ref={inputRef}
value={value}
onChange={(event) => {
setValue(event.target.value);
if (handler) {
handler(event.target.value);
}
}}
/>
</div>
);
});
const App = () => {
const Inputef = React.useRef<InputRef>(null);
const [value, setValue] = React.useState("");
const handler = React.useCallback(
(value: string) => {
setValue(value);
},
[setValue]
);
React.useEffect(() => {
Inputef.current?.focus();
Inputef.current?.register(handler);
}, [Inputef, handler]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Input ref={Inputef}></Input>
<h2>Autofocuses and passes changed value to the parent</h2>
<div>Editing: {value}</div>
</div>
);
};
const rootElement = document.getElementById("root")!;
const root = createRoot(rootElement);
root.render(<App />);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment