Skip to content

What is the equivalent of document.getElementById() in React

May 25, 2022Abhishek EH2 Min Read
What is the equivalent of document.getElementById() in React

If you have used vanilla JavaScript before, you might have used document.getElementById() almost every day. $(selector).val() in case you were using jQuery.

In this article, we will see how to achieve the same in React and will learn how to read the value of text input.

Project setup

Create a new react project using the following command:

1npx create-react-app react-get-element-by-id

Add an input text and a submit button in App.js:

1import "./App.css"
3function App() {
4 const submitHandler = e => {
5 e.preventDefault()
6 }
8 return (
9 <div className="App">
10 <form onSubmit={submitHandler}>
11 <input name="name" />
12 <input button type="submit" value="Submit" />
13 </form>
14 </div>
15 )
18export default App

We have also added a submit handler for the form to prevent default submit (redirection).

Using useRef hook

In React, we can make use of the useRef hook to access the reference to a DOM element.

1import { useRef } from "react"
2import "./App.css"
4function App() {
5 const submitHandler = e => {
6 e.preventDefault()
7 alert("Name is " + inputRef.current.value)
8 }
10 const inputRef = useRef(null)
12 return (
13 <div className="App">
14 <form onSubmit={submitHandler}>
15 <input name="name" ref={inputRef} />
16 <input button type="submit" value="Submit" />
17 </form>
18 </div>
19 )
22export default App

If you run the above code, enter your name in the text box and click on submit, you should be able to see an alert with your name.

Hence refs are the equivalent to document.getElementById() in React.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2023 CodingDeft.Com