If you're working with React, you're probably familiar with the concept of JavaScript DOM manipulation. It's basically the way to update the website, by changing the appearance of website elements, or in other words "nodes".
But to manipulate the nodes, we need to find them first. And that's exactly where the querySelector
function comes into play. The usage of this method is very straightforward, but what's not so obvious is how to use it in React. Or if you should do it at all.
All these questions will be answered in this article. And by the time you're done reading it. You'll understand the basic overview of querySelector function, how to use it in React, and if you should use it in React at all.
But first, let's start with the basics of this method.
What Is QuerySelector
To put it as simply as we can, querySelector is a method for finding elements on any website.
The Document method
querySelector
returns the firstElement
within the document that matches the specified selector, or group of selectors. If no matches are found,null
is returned. (source: MDN)
This method is a part of the Document
interface.
The
Document
interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree. (source: MDN)
To find an element using querySelector, we need to specify it using a proper selector. For example, to find an element <div id="text"></div>
, we would need to write the following selector.
Finding an element based on its id
document.querySelector("#text");
Or to find an element <div class="text"></div>
, we'd need to modify our original selector in the following fashion.
Finding an element based on its class
document.querySelector(".text");
As you can see, using this method is no rocket science. But it becomes a bit more complicated when we try to use this method in React.
Can You Use QuerySelector in React?
If you're working with React, you're probably familiar with the concept of a "virtual DOM" - a JavaScript representation of the actual DOM. This is what React uses to determine what changes need to be made to the actual DOM.
info
If you're not familiar with React Virtual DOM, check out our article where we compare React virtual DOM and real DOM.
One of the benefits of the virtual DOM is that it allows React to optimize updates to the UI. When React is working with the virtual DOM, it can batch together multiple changes and then apply them all at once to the actual DOM. This is more efficient than making individual changes to the DOM, and it helps to avoid potential issues with React components getting out of sync with the actual DOM.
When you try to modify the element that was retrieved using querySelector, you're no longer taking the advantage of React virtual DOM. It's still possible to use querySelector in React, however, React encourages developers not to use it. Instead, we should aim to use refs
if possible.
Refs provide a way to access DOM nodes or React elements created in the render method. (source: React)
tip
Using querySelector in React is not incorrect and it won't break your functionality. However, it is preferred to use an approach provided by the React framework. Mostly because it comes with certain benefits and optimizations.
Now that we know if we can use this method or not, let's see how to do it in React.
Using QuerySelector in React
In this section, we'll see how to use querySelector in React, and we'll demonstrate that in the following example.
Let's consider a simple application. When the user clicks on a button, we want the page to scroll so the user can see and read the website header. We can implement the given behavior in the following fashion.
Scrolling to an element using querySelector
const App = () => {
const scrollToHeader = () => {
document.querySelector("#head").scrollIntoView();
};
return (
<section className="App">
<header id="head">Hello User</header>
<main>
<p>Awesome content</p>
<button onClick={scrollToHeader}>Scroll To Header</button>
</main>
<footer>Interesting Links</footer>
</section>
);
};
export default App;
This example works just fine, and it won't break anything. But as we already mentioned, React encourages us to use a different approach. To be more concrete, it encourages us to use React Refs.
If we want to rewrite our example above based on React guidelines, our final code snippet will need to change slightly.
Scrolling to an element using React ref
import { useRef } from "react";
const App = () => {
const headerRef = useRef();
const scrollToHeader = () => {
headerRef.current.scrollIntoView();
};
return (
<section className="App">
<header ref={headerRef}>Hello User</header>
<main>
<p>Awesome content</p>
<button onClick={scrollToHeader}>Scroll To Header</button>
</main>
<footer>Interesting Links</footer>
</section>
);
};
export default App;
In this example, we're using a reference to header
component. And performing a scroll in the same way as we did in the example before.
Concluding Thoughts
The querySelector is a built-in function in JavaScript that allows you to select an element in the DOM by its id, class, or tag name. When modern JavaScript frameworks like React weren't around, developers didn't have any other choice, but to use it.
But nowadays, when using React, we don't see this method being used that often. And there is a good reason for that. Modern frameworks provide us with different ways to manipulate the DOM. And at the end of the day, we don't have to use querySelector method directly.
Luckily, for the few developers that still want to use this method, we have this article. And here, we covered what querySelector is. We also answered the question if it's possible to use it in React. And lastly, we showcased how to use querySelector in React.
With all this information in mind, you should know when to use querySelector, and how to use querySelector. But most importantly, you know if you need to use it at all.