Skip to content

Instantly share code, notes, and snippets.

@jamesreggio
Last active January 8, 2023 21:40
Show Gist options
  • Save jamesreggio/142215754ad06f375bd87657c6227ed8 to your computer and use it in GitHub Desktop.
Save jamesreggio/142215754ad06f375bd87657c6227ed8 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 {
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();
}
}
@Kazerian
Copy link

Yes, i have the same question. can anyone mention the usecase of forwardRef that cant be achieved by sending refs as props? there must be a reason for introducing forwardRef

Have a look at this code https://codesandbox.io/s/snowy-feather-yrsjwn?file=/src/App.js
It is a simple example of both, passing ref as props as well as using forwardRef

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