What are React refs?

August 03, 2018

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:

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:

  1. I define an input and add ref="foo".
  2. I can then access that input with this.refs.foo.value.
class Input extends Component {
	triggerAlert = () => {

	render() {
		return (
			<form onSubmit={this.triggerAlert}>
				<input ref="foo" />

Get the articles and announcements that I never post publicly: