Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save d4rkm3z/bed67e1d204af3663389c088e23eff18 to your computer and use it in GitHub Desktop.

Select an option

Save d4rkm3z/bed67e1d204af3663389c088e23eff18 to your computer and use it in GitHub Desktop.
Simple example usage of React.forwardRef()
// 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 {
constructor(props) {
super(props);
this.emailRef = React.createRef();
}
render() {
return (
<div>
<EmailInput ref={this.emailRef} />
<button onPress={() => this.emailRef.current.focus()}>
Click me to focus email
</button>
</div>
);
}
}
// `this.emailRef.current` points to the `input` component inside of EmailInput
// (instead of EmailInput itself), because EmailInput is using React.forwardRef
// to 'forward' its ref onward. This makes it possible to call `focus`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment