Forked from jamesreggio/react-forwardref-simple-example.js
Created
April 28, 2020 18:53
-
-
Save d4rkm3z/bed67e1d204af3663389c088e23eff18 to your computer and use it in GitHub Desktop.
Simple example usage of React.forwardRef()
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
// EmailInput wraps an HTML `input` and adds some app-specific styling. | |
const EmailInput = React.forwardRef((props, ref) => ( | |
<input ref={ref} {...props} type="email" className="AppEmailInput" /> | |
)); | |
class App extends Component { | |
emailRef = React.createRef(); | |
render() { | |
return ( | |
<div> | |
<EmailInput ref={this.emailRef} /> | |
<button onClick={() => this.onClickButton()}> | |
Click me to focus email | |
</button> | |
</div> | |
); | |
} | |
// `this.emailRef.current` points to the `input` component inside of EmailInput, | |
// because EmailInput is forwarding its ref via the `React.forwardRef` callback. | |
onClickButton() { | |
this.emailRef.current.focus(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment