Skip to content

Latest commit

 

History

History
38 lines (27 loc) · 1.52 KB

13.useRef()Hook.md

File metadata and controls

38 lines (27 loc) · 1.52 KB

Easily Access and Modify DOM Nodes with useRef in React

In React, a ref is a way to access the properties of a DOM element. Refs are created using React's createRef function and attached to React elements via the ref 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.