Mark As Completed Discussion

In React, the useRef hook is often used for handling form input values and focus management. Let's explore how to use the useRef hook for working with forms.

To begin, let's create a simple form component that logs the value of an input field when the form is submitted:

JAVASCRIPT
1import React, { useRef } from 'react';
2
3function MyForm() {
4  const inputRef = useRef();
5
6  const handleSubmit = (e) => {
7    e.preventDefault();
8    console.log(inputRef.current.value);
9  }
10
11  return (
12    <form onSubmit={handleSubmit}>
13      <input ref={inputRef} type="text" />
14      <button type="submit">Submit</button>
15    </form>
16  );
17}

In this example, we create a ref variable inputRef using the useRef hook. We attach this ref to the input field using the ref prop. When the form is submitted, the value of the input field is logged to the console using inputRef.current.value.

The useRef hook is also useful for managing focus within forms. For example, you can automatically focus on an input field when the form renders:

JAVASCRIPT
1import React, { useEffect, useRef } from 'react';
2
3function MyForm() {
4  const inputRef = useRef();
5
6  useEffect(() => {
7    inputRef.current.focus();
8  }, []);
9
10  const handleSubmit = (e) => {
11    e.preventDefault();
12    console.log(inputRef.current.value);
13  }
14
15  return (
16    <form onSubmit={handleSubmit}>
17      <input ref={inputRef} type="text" />
18      <button type="submit">Submit</button>
19    </form>
20  );
21}

In this modified example, we use the useEffect hook to focus on the input field when the form renders. The empty array [] as the second argument ensures that the effect is only run once during the initial render.

The useRef hook provides an elegant way to handle form input values and manage focus within forms in React. It is a powerful tool to have in your React Hooks toolkit.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment