Created
July 26, 2022 09:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://codesandbox.io/s/useimperativehandlecomponenterror-forked-4u0vy6?file=/src/App.tsx