Skip to content

Instantly share code, notes, and snippets.

@ericvicenti
Created February 4, 2019 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericvicenti/7c38478f264314605124b41cd06f720f to your computer and use it in GitHub Desktop.
Save ericvicenti/7c38478f264314605124b41cd06f720f to your computer and use it in GitHub Desktop.
import React, { forwardRef, useRef } from "react";
const Input = forwardRef((props, ref) => (
<input type="text" ref={ref} className="input" {...props} />
));
function doSideEffect() {
alert("hey, focused!");
}
const MyInput = forwardRef((props, ref) => {
const innerInput = useRef(null);
function focus() {
doSideEffect();
innerInput.current && innerInput.current.focus();
}
ref.current = { focus };
return <Input {...props} ref={innerInput} />;
});
export default function App() {
const input = useRef(null);
return (
<div className="App">
<button
onClick={() => {
input.current && input.current.focus();
}}
>
Click me
</button>
<MyInput ref={input} value="hello" />
</div>
);
}
@ericvicenti
Copy link
Author

discussion: reactjs/rfcs#103

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment