Table of Contents
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"23function App() {4 const submitHandler = e => {5 e.preventDefault()6 }78 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 )16}1718export 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"34function App() {5 const submitHandler = e => {6 e.preventDefault()7 alert("Name is " + inputRef.current.value)8 }910 const inputRef = useRef(null)1112 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 )20}2122export 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