Refs provides a way to access DOM nodes or React elements created in the Render method.
Refs Usage scenario
In some cases, we need to force changes to subcomponents outside of the typical data flow. The subcomponent may be an instance of the React component or a DOM element, for example:
- Manage focus, text selection or media playback.
- Trigger the forced animation.
- Integrate third-party DOM libraries.
Create the Refs
this.myRef = React.createRef();
Copy the code
Creation method:
-
CreateRef (support for use inside function components and class components)
-
UseRef (for use within function components only)
Create Refs with React.useref () and attach them to the React element via the ref attribute.
const refContainer = useRef(initialValue); Copy the code
The ref object returned by useRef remains constant throughout the life of the component.
// react.useref () differs from react.createref () :
import React, { useRef, useEffect, createRef, useState } from 'react';
function MyInput() {
let [count, setCount] = useState(0);
const myRef = createRef(null);
const inputRef = useRef(null);
// Execute only once
useEffect(() = > {
inputRef.current.focus();
window.myRef = myRef;
window.inputRef = inputRef; } []); useEffect(() = > {
// createRef is false every time except the first time
console.log('myRef === window.myRef', myRef === window.myRef);
// always true [useRef]
console.log('inputRef === window.inputRef', inputRef === window.inputRef);
})
return (
<>
<input type="text" ref={inputRef}/>
<button onClick={()= > setCount(count+1)}>{count}</button>
</>)}Copy the code
Access to the Refs
When a ref is passed to an element in render, a reference to that node can be accessed in the ref’s current property
const node = this.myRef.current;
Copy the code
The value of ref varies depending on the type of node:
- when
ref
Attribute is used in the constructor when used for HTML elementsReact.createRef()
To create theref
Receive the underlying DOM element as itcurrent
Properties. - when
ref
Property for custom class components,ref
Object receives a mount instance of the component as itcurrent
Properties. - You cannot use ref attributes on function components because they have no instances.
Refs and function components
By default, you cannot use the ref attribute on function components because they have no instances.
You can use the ref attribute inside a function component as long as it points to a DOM element or a class component
function CustomTextInput(props) {
// textInput must be declared here so that ref can reference it
const textInput = useRef(null);
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input type="text" ref={textInput} />
<input type="button" value="Focus the text input" onClick={handleClick} />
</div>
);
}
Copy the code
Expose the DOM Refs to the parent component
Refs forward
Forward refs to the DOM component
Ref forwarding is a technique for automatically passing a Ref through a component to one of its children.
const FancyButton = React.forwardRef((props, ref) = > (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can get the DOM button ref directly:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Copy the code
A step-by-step explanation of what happens in the example above:
- We create a React ref and assign it to the ref variable by calling React. CreateRef.
- We pass ref down to the JSX attribute by specifying it as a JSX attribute.
- React passes ref to the function (props, ref) =>… , as its second parameter.
- We forward the ref parameter down to specify it as a JSX property.
- When ref is mounted, ref. Current will point to the DOM node.
The callback Refs
Instead of passing the ref attribute created by createRef(), you pass a function. This function takes React component instances or HTML DOM elements as arguments so that they can be stored and accessed elsewhere.
You can pass refs in the form of callbacks between components, just as you can pass refs for objects created through React. CreateRef ().
Reference article:
- Refs and the DOM
- Refs forward
- Hook API index