1/*
2 A common use case is to access a child imperatively:
3*/
4
5function TextInputWithFocusButton() {
6 const inputEl = useRef(null);
7 const onButtonClick = () => {
8 // `current` points to the mounted text input element
9 inputEl.current.focus();
10 };
11 return (
12 <>
13 <input ref={inputEl} type="text" />
14 <button onClick={onButtonClick}>Focus the input</button>
15 </>
16 );
17}
1import React, { useRef } from 'react';
2
3function TextInputWithFocusButton() {
4 const inputEl = useRef(null);
5 const onButtonClick = () => {
6 // `current` points to the mounted text input element
7 inputEl.current.focus();
8 };
9 return (
10 <>
11 <input ref={inputEl} type="text" />
12 <button onClick={onButtonClick}>Focus the input</button>
13 </>
14 );
15}
1function TextInputWithFocusButton() {
2 const inputEl = useRef(null);
3 const onButtonClick = () => {
4 // `current` points to the mounted text input element
5 inputEl.current.focus();
6 };
7 return (
8 <>
9 <input ref={inputEl} type="text" />
10 <button onClick={onButtonClick}>Focus the input</button>
11 </>
12 );
13}
1const refContainer = useRef(initialValue);
2//useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).
3//The returned object will persist for the full lifetime of the component.