This article describes how to use Ref in React. Share it for your reference, as follows:
Use of Ref in React React v16.6.3
In a typical React data stream, props are the only way for a parent component to interact with its child components. To modify a child, re-render it using new props. However, in some cases, it is necessary to force modification of the child outside the typical data flow. The child to be modified can be an instance of the React component or a DOM element. For both cases, React provides api.
When to use refs
Refs has some good use cases:
- 1. Text selection or media playback.
- 2. Trigger the imperative animation.
- 3. Integrate with third-party DOM libraries.
Avoid using refs for any operations that can be done declaratively.
*Don't overuse Refs
Old API: String references
If you have used React before, you may be familiar with an old API where the ref property is a string "textInput" and the DOM node is accessed as. It is recommended not to use it because there are some problems with string references that are considered legacy issues and are likely to be removed in a future version.
Callback reference
When the component is installed, React will call the ref callback using the DOM element and call null on uninstall.
Refs is guaranteed to be up to date until componentDidMount or componentDidUpdate triggers.
class CustomTextInput extends { constructor(props) { super(props); = null; = element => { = element; }; = () => { // Focus the text input using the raw DOM API if () (); }; } componentDidMount() { // autofocus the input on mount (); } render() { // Use the `ref` callback to store a reference to the text input DOM // element in an instance field (for example, ). return ( <div> <input type="text" ref={} /> <input type="button" value="Focus the text input" onClick={} /> </div> ); } }
refs example--click to get input focus
class Example extends { handleClick() { // Get focus using the native DOM API (); } render() { // After the component is inserted into the DOM, the ref property adds a reference to the component. return ( <div> <input type="text" ref="myInput" /> <input type="button" value="Click on the me input box to get focus" onClick={(this)} /> </div> ); } }
use()
() API introduced in React 16.3. If you are using an earlier version of React, we recommend that you use callback references.
create()
Refs is created using attributes, () and attached to the React element through the ref attribute. When constructing a component, Refs are usually assigned to instance properties so that they can be referenced throughout the component.
class MyComponent extends { constructor(props) { super(props); = (); } render() { return <div ref={} />; } }
Visit ref
When a ref is passed to an element render, a reference to the node becomes accessible at the currentref property
const node = ;
The value of ref varies according to the type of node
- When using this property on a refHTML element, the attribute created by ref in the constructor will receive () the underlying DOM element as its current property.
- When using this property on a ref custom class component, the ref object takes the installed instance of the receiving component as its current.
You may not be able to use ref on function components because they have no instances.
class CustomTextInput extends { constructor(props) { super(props); // create a ref to store the textInput DOM element = (); = (this); } focusTextInput() { // Explicitly focus the text input using the raw DOM API // Note: we're accessing "current" to get the DOM node (); } render() { // tell React that we want to associate the <input> ref // with the `textInput` that we created in the constructor return ( <div> <input type="text" ref={} /> <input type="button" value="Focus the text input" onClick={} /> </div> ); } }
current When the component is installed, React will assign the DOM element to the property and null assign it back when uninstalled. The ref update occurs before componentDidMount or componentDidUpdate lifecycle method.
Cannot use ref attribute on function components
function MyFunctionComponent() { return <input />; } class Parent extends { constructor(props) { super(props); = (); } render() { // This will *not* work! return ( <MyFunctionComponent ref={} /> ); } }
**If you need to reference it, you should convert the component to a class just like you would when you need a lifecycle method or state.
However, as long as you refer to a DOM element or class component, you can use the ref attribute in a function component: **
function CustomTextInput(props) { // textInput must be declared here so the ref can refer to it let textInput = (); function handleClick() { (); } return ( <div> <input type="text" ref={textInput} /> <input type="button" value="Focus the text input" onClick={handleClick} /> </div> ); }
Expose DOM reference to parent component
In rare cases, it may be desirable to access the DOM node of the child node from the parent component. This is not usually recommended as it breaks the component encapsulation, but it can occasionally be used to trigger focus or measure the size or position of the child DOM node.
While it is possible to add references to child components, this is not an ideal solution, as only component instances are obtained instead of DOM nodes. Also, this does not apply to functional components.
If using React 16.3 or later, we recommend using ref forwarding in these cases. Reference forwarding allows a component to choose to expose a reference to any child component as its own component. A detailed example of how to expose a child DOM node to a parent component can be found in the ref forwarding documentation.
If you are using React 16.2 or lower, or you need more flexibility than ref forwarding provides, you can use this alternative and explicitly pass ref as a prop of different names.
It is recommended not to expose the DOM node if possible, but it can be a useful escape pod. Note that this method requires adding some code to the child component. If you have no control over the child component implementation at all, the last option is to use findDOMNode(), but it is not encouraged to use StrictMode.
I hope this article will be helpful to everyone's react programming.