Created
February 4, 2019 07:11
-
-
Save ericvicenti/7c38478f264314605124b41cd06f720f to your computer and use it in GitHub Desktop.
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 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> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
discussion: reactjs/rfcs#103