In React, a
ref
is a way to access the properties of a DOM element. Refs are created using React'screateRef
function and attached to React elements via theref
attribute.
Here's an example of how you might use a ref to access the value of an input element:
import React, { useRef } from "react";
function InputForm() {
const inputEl = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
console.log(inputEl.current.value);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={inputEl} />
</label>
<button type="submit">Submit</button>
</form>
);
}
In this example, the inputEl
ref
is created using the useRef
hook and attached to the input element via the ref
attribute. When the form is submitted, the handleSubmit function is called, and the value of the input element is logged to the console using the inputEl.current.value
property.
There are a few reasons why you might want to use refs in your React application:
-
DOM manipulation: Refs can be useful for manipulating the DOM directly, such as focusing an input element or getting the value of a form field.
-
Third-party libraries: Refs can be useful for interacting with third-party libraries that require direct access to DOM elements.
-
Performance optimization: In some cases, using refs can be more performant than using the state or props of a component to manipulate the DOM.