import React, { useRef } from 'react';
function InputExample() {
const inputRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
console.log(inputRef.current.value);
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={inputRef} />
</label>
<button type="submit">Submit</button>
</form>
);
}
In this example, the useRef hook is used to create a ref for the tag, which is initially set to null. When the form is submitted, the handleSubmit function is called, which logs the current value of the tag using the inputRef.current.value syntax.
By using ref, you can perform operations such as focusing on the input field, getting the current value of the input, or manipulating the input field in other ways.
I hope that helps! Let me know if you have any further questions.
Jisoo P
then why you called useRef to useRef 'hook'?
Good question! useRef is called a "hook" because it is a function provided by React that lets you use state and other React features in functional components.
In React, functional components are a simpler and more lightweight way to define components than class components. However, functional components don't have access to the this keyword, and therefore can't use instance variables or lifecycle methods.
Hooks were introduced in React 16.8 as a way to provide functional components with some of the same features as class components. useRef is one of the many hooks provided by React that allows you to manage state or access to DOM elements in a functional component.
By calling useRef inside your component, you create a reference object that you can attach to a DOM element using the ref attribute. You can then use this reference object to manipulate the DOM element or access its properties, such as its current value.
I hope that clears up any confusion! Let me know if you have any other questions.