Search⌘ K
AI Features

Accessing DOM Elements

Explore how to access and manage DOM elements in React using the useRef hook. Understand React’s abstraction of the DOM, challenges of direct DOM manipulation within components, and how useRef provides a safe, lifecycle-aware way to interact with element instances.

Direct DOM manipulation before React

Before a modern UI framework was introduced, to make a change to the screen, we worked directly with a DOM element. In the code below, a basic HTML body is combined with JavaScript to modify the content of an h1 element.

HTML
<!-- HTML Body with an h1 element and a specified ID -->
<body>
<h1 id="title"></h1>
</body>
<!-- JavaScript script to set the text content of the h1 element with id 'title' -->
<script>
// Get the element by ID
const el = document.getElementById('title');
// Set the text content to "Hello World"
el.textContent = "Hello World";
</script>

The preceding HTML file defines an h1 element tagged with a specific id value. So we can use the id value to find the el element and make a change to its textContent. This is how a DOM element gets updated:

HTML displaying the Hello World title
HTML displaying the Hello World title

React component abstraction

With React, we can achieve the preceding functionality by wrapping elements in a component, such as a function component:

const Title = () => {
// State to hold the title
const [title, setTitle] = useState("");
// useEffect to set the title to "Hello World" on component mount
useEffect(() => {
setTitle("Hello World");
}, []);
// Render the h1 element with the dynamically set title
return <h1>{title}</h1>;
}
Functional component using state and useEffect to set and display a title

The benefits of using this functional approach are that it provides an abstractionAbstraction refers to the process of hiding complex implementation details and presenting a simplified and high-level interface to users. on top of the physical DOM and allows us to focus our development in a ...