Created
July 17, 2020 19:15
-
-
Save apackin/7e53e60cb7fc19c7ad9339acd09ff373 to your computer and use it in GitHub Desktop.
App with useImperativeHandle
This file contains hidden or 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
| function App() { | |
| const [text, setText] = useState("Fun"); | |
| const fancyRef = useRef(); | |
| const submitButton = () => { | |
| setText(fancyRef.current.value); | |
| }; | |
| return ( | |
| <div id="App"> | |
| <p>Submitted Text from forwardRef: {text}</p> | |
| {/* This ref is forwarded directly to the DOM element designated by FancyTextSubmit */} | |
| <FancyTextSubmit ref={fancyRef} onClick={submitButton} /> | |
| </div> | |
| ); | |
| } | |
| const FancyTextSubmit = forwardRef(({ onClick }, forwardRef) => { | |
| const inputRef = useRef(); | |
| useImperativeHandle(forwardRef, () => inputRef.current); | |
| const onButtonClick = e => { | |
| onClick(e); | |
| // `current` points to the mounted text input element | |
| inputRef.current.focus(); | |
| }; | |
| return ( | |
| <div> | |
| <input ref={inputRef} type="text" /> | |
| <button onClick={onButtonClick}>Submit</button> | |
| </div> | |
| ); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment