React refs let you reference elements in the DOM. They’re ways to modify elements outside of the typical data flow in React. They should be used sparingly – the general rule of thumb is to avoid using them entirely (in favor of managing interaction through props
instead), although there are three occasions when you have no other option:
- Managing focus, text selection, or media playback.
- Integrating with third-party DOM libraries.
- Triggering imperative animations.
You might ask, “Why can’t I just use document.getElementById(...)
to reference something in the DOM?” The answer: well, you can.
But, IDs only work on a single element in the whole DOM tree, so if you have more than one object with the same ID, only the first one will be targeted. That’s why refs are a better choice.
In action, they look something like the following:
- I define an
input
and addref="foo"
. - I can then access that input with
this.refs.foo.value
.
class Input extends Component {
triggerAlert = () => {
alert(this.refs.foo.value)
}
render() {
return (
<form onSubmit={this.triggerAlert}>
<input ref="foo" />
</form>
)
}
}