Skip to content

Instantly share code, notes, and snippets.

@apackin
Created July 17, 2020 19:15
Show Gist options
  • Select an option

  • Save apackin/7e53e60cb7fc19c7ad9339acd09ff373 to your computer and use it in GitHub Desktop.

Select an option

Save apackin/7e53e60cb7fc19c7ad9339acd09ff373 to your computer and use it in GitHub Desktop.
App with useImperativeHandle
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