Access DOM Node Use React Ref

Image for post
Image for post
how useRef is so confusing…

Not long again, I posted a short note about using useRef hook in react as an instance variable which can be referenced alongside the lifespan of a component.

Recently, I discovered another usage of Ref to access DOM nodes/React elements. The reason for us to be able to do this is that Refs are created using React.createRef() and attached to React elements via the ref attribute.

So when we want to access a DOM node/React element (e.g. a customised React component), we can do something like:

import React, { useRef } from "react";

The equivalent when using the original flavour of createRef API in class component is :

import React, { Component, createRef } from "react";

In the above example, we try to access DOM node directly. When it comes to React element, further to the point regarding ref attribute is that it shouldn’t be used on functional components. Reason behind it is that they don’t have instances. (Obviously, function vs. class).

So if we change the above example to:

import React, { Component, createRef } from "react";
import { ChildComponent } from "react";

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store