Accessing DOM Elements
Learn how React uses a virtual DOM for efficient DOM updates and how refs serve as a means to directly work with DOM elements in the framework.
We'll cover the following...
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.
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:
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 titleconst [title, setTitle] = useState("");// useEffect to set the title to "Hello World" on component mountuseEffect(() => {setTitle("Hello World");}, []);// Render the h1 element with the dynamically set titlereturn <h1>{title}</h1>;}
The benefits of using this functional approach are that it provides an