In this article, we will learn how to set and get input field data in React.
There are two ways in which we can access and set the values on the input fields in React.
- Making the fields controlled.
- Creating a reference to the input fields.
Creating controlled components to get and set input field data in React
In React, we maintain the states in the components that are used to store the data as we cannot store them in variables because during the re-render the variables will be redefined.
Thus the states can be used to control the value of the input fields.
import { useState } from "react"; const App = () => { const [inputValue, setInputValue] = useState(""); return ( <div className="App"> <input type="text" placeholder="write something" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> </div> ); };
Here we defined the state with the initial value of empty string ""
and then we have a method to update the state setInputValue
that updates the state whenever the value of the input fields is changed.
We are listening to the onChange
event and invoking setInputValue
to update the new value. Also, we set the value of the input field to be what is in the state. Thus it keeps the input controlled, even if re-render happens.
Creating a reference to the input fields.
Another way to set and get the input field values is by creating a reference to the input element. You can use the useRef()
hook to create the reference.
import { useRef } from "react"; const App = () => { const inputRef = useRef(); const handleClick = () => { console.log(inputRef.current.value); }; return ( <div className="App"> <input ref={inputRef} type="text" placeholder="write something" /> <button onClick={handleClick}>Click me</button> </div> ); };
useRef()
creates an object and the key current holds the reference to the DOM elements, thus access them as inputRef.current.value
Here we are getting the input field value on the button click but the input field is not controlled and if the component re-renders, it will lose its value.
Thus this approach should be used cautiously.