Aaron Connolly

React Refs

What is a ref in React?

Stumble with me through React, a web browser and the fuzzy grey area between.

Background

Recently, I decided to read through all of the React documentation to better understand the framework and to try and pick up things I might have missed. Though I had worked with React a bit, I had not ventured into the documentation until I needed to know something specific. In hindsight, I wish I read through them sooner because they are fantastic.

When I came to Refs and the DOM I wondered why anyone would need this functionality. React Components are an abstraction of the native DOM elements that your browser renders along with their attributes and various functions. React has a normal “data flow” thorugh these components managed by props and state and so it seemed that with them you could drive the values of any property on any HTMLElement about and get the behavior you want.

The Confusion

Check out the methods for the HTMLElement. This means, that in the example from the Refs and the DOM an input HTMLElement does not have a focused property, rather it has a .focus() function. You can’t easily use props, state or the view lifecycle to manipulate a custom input Component to auto-focus. In React, it is useful to have a reference to this DOM element so that you can call .focus() on it. I think this is what is meant by an “escape hatch”.

References