Whenever we want to access data of input elements we use useState() hook to get input forms values or some other hooks, and this basically helps to manage to react states.
But not all the time we need to manage to react state, sometimes we just want to access the HTML element values for just reading purposes.
Refs are basically the reference to the Dom elements.
So if we want to get values of input fields without taking care of react states or without using useState(), then we can use Refs.
Let’s understand this with the help of code.
Here we created a component file with the name Refs.js, and we are calling this component inside the App.js file.
import './App.css';
import Refs from './Refs';
function App() {
return (
<>
<Refs/>
</>
);
}
export default App;
Now inside the Refs.js file, we have created a form with an input field for taking input as a username, this form is submitted when the user clicks on submit button, on submit of this form a method called submitData is executing.
First, let’s see the Refs.js file code and then understand it.
import React,{useRef} from 'react';
const Refs= ()=>{
const username = useRef();
const submitData=(event)=>{
event.preventDefault();
console.log(username);
console.log(username.current.value);
}
return (
<form onSubmit={submitData}>
<input type="text" placeholder='Enter Username' ref={username}/>
<button type="submit">Submit</button><br/>
</form>
)
}
export default Refs;
Before doing anything first we need to import this useRef hook and we have to assign it to a constant variable username.
const username = useRef();
This username is referencing the input type text filed with this property ref={username}
<input type="text" placeholder='Enter Username' ref={username}/>
Now submitData function we are displaying this reference variable value.
As it is an HTML DOM reference variable, it has many properties, and it returns an object with different properties.
We can access this variable value by its properties, username.current.value
So whatever we write inside the input text we can get that value by using this username.current.value
Here is the output which helps you to visualize the actual work.
On the above image, you can see we console the username and we got this object which has a current property that has a value property so by consoling username.current.value we can get the name we have entered in the input field.
Controlled and Uncontrolled components :
So basically component which uses useState or other hooks to manage to react states is a controlled component and which uses Refs for getting the value of input fields is uncontrolled components because with Refs we cannot manage to react states.