Refs and DOM in React

Saurav Bhagat
3 min readAug 26, 2019

--

Image by patric- unsplash

If you are here, it means you might have came across the word ‘refs’ while developing react applications or while looking for some answers in stackoverflow. So, in this article I’m going to explain refs in as plain way as possible.

Traditionally, to access a DOM element, we do things like:

document.getElementByID('cool');

And after that we access properties and methods of that element inside our script. But can you ask yourself, how are you acheiving this currently in react? Think about it and then this article will be of great help to you.

Think of a input element <input type="text" id="cool" />

We can easily get its value using above method, but in react we achieve this mostly using, binding a state variable with each input and then updating the value in a function — Heavy use of state for such simple task. Here come Refs.

Refs provide a way to access DOM nodes or React elements created in the render method.’

Now, instead of id, we give refs <input type="text" ref={this.inputRef} />

where inputRef is a property which we create in constructor similar to state variable using createRef( ) function.

creating refs property using createRef( )

Now, to access the value of that input field anywhere:

this.inputRef.current.value

CreateRef( ) creates the current object here, which we need to add to use any properties or methods of that DOM element.

Basic use of refs

Refs is not limited to input fields only. You can take it as, wherever you were using other DOM methods you can use ref there. However, official docs suggest to not use refs heavily.

Now, I’ll show you how to access other component methods using ref, we’ll make 2 classes, a parent class and a child class which is nothing but a input field and we will access the function of child component in the parent component using refs. Since, it’s also a part of DOM.

Child component
Parent component

Here in Parent class, we have used focusInput method of child class. Consider child class as a HTML input element with focusInput method present. We gave ref to Input component(child) and using that ref, we are accessing its method. Simple, Right?

I hope this was a good read. I usually write articles on React, you can follow me on medium.

Beginners guide to React Hooks

--

--