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.
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 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 IDconst 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:
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