Access a DOM Element in React

  1. Alternative to getElementById() in React
  2. Refs in React Functional Components
  3. Refs in React Class Components

React is a JavaScript-based framework, but it operates with a virtual DOM. React API comprises different methods and properties than those of native JavaScript.

When building web applications, developers often use Document.getElementById() method. This method can specify the id and work with specific HTML elements.

Alternative to getElementById() in React

React has its own rules and layers of systems built on top of the native JavaScript interface. To access specific DOM nodes in React, we have to use refs instead of using the Document.getElementById() method.

Refs can be used for many different purposes, such as getting the value entered into input elements, controlling the appearance of elements when focused, playing animations, and more.

Still, by default, React follows a declarative approach for building the UI of the application. Refs are an exception to this approach, so they should be used only in exceptional cases.

Refs in React Functional Components

Since the introduction of hooks in React v16.8, developers can create refs in functional components. The useRef hook can be imported from the core React library.

Let’s take a look at this example.

import "./styles.css";
import { useRef } from "react";
export default function App() {
  const header = useRef(null);

  return (
    <div className="App">
      <h1 ref={header}>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

We initialize the header variable to a ref with a null value.

In JSX, we set the ref attribute of the <h1> element to this variable. Then we console.log() the variable, and if you check the console on this live demo, the variable contains the value representing the <h1> DOM node.

Refs in React Functional Components

Refs in React Class Components

React developers can also use Class syntax to create components. In this example, we have a component that does the same thing as the functional component in the previous example.

class App extends React.Component {
  constructor(props) {
    this.header = React.createRef();
  render() {
      return <h1 ref={this.header}>Hello CodeSandbox</h1>;

The main difference is the syntax. We use the React.createRef() method to set up the ref.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - React Element

  • CloneElement Method in React
  • CreateElement Method in React
  • Props and Children in React