I Love ReactJS

Increase the flexibility of React components: learn more about the wonderful uses of forwardRef API

yesterday we discussed the useRef hook function in React: only this article, let you fully master the useRef hook function in React, one of the scenarios is to use useRef in the function component to create a ref object, and then bind it to an element to get a reference to that element in order to do various operations on the referenced element. What do we do when we want to access a reference to a child component in the parent component?

The

answer is achieved through React's forwardRef API.

first acquaintance of forwardRef API

forwardRef API allows us to pass a ref from the parent component to the child component, thus giving the parent component access to the DOM node or instance of the child component. The syntax is as follows:

const SomeComponent = forwardRef(render);

generally speaking, we can let the parent component access the child component through the callback function, that is, pass the callback function to the child component through props to access the DOM node or instance of the child component in the parent component. But in some cases, this approach is not convenient or flexible enough. forwardRef provides a more flexible way to solve this problem.

when we wrap the subcomponents with forwardRef , we can access the subcomponents through the second parameter ref of forwardRef . The ref is then passed to the element or component that needs to be referenced in the child component so that the parent component can access the child component's instance or DOM node. This makes forwardRef a very powerful and flexible tool that can help us easily access and manipulate elements or components in subcomponents.

how to use forwardRef API

to use forwardRef to access the DOM node or instance of a child component, one of the following two steps is indispensable:

  1. wrap sub-components through forwardRef

    in the parent component, pass the ref parameter to the child component wrapped by the forwardRef function so that the parent component:

       const   ChildComponent  =  forwardRef  ( ( props, ref ) = & gt;  {
     / / subcomponent code 
    });
     copy code   

    forwardRef wraps a functional component, and the second argument to the function is the ref object passed by the parent component. You can use the useRef method we discussed in the previous article to create a ref object in the parent component.

  2. access ref objects

    in child components

    in the child component, bind the ref object to the element or component that needs to be accessed, so that the parent component can access an instance of the DOM element or component.

       const   ChildComponent  =  forwardRef  ( ( props, ref ) = & gt;  {
     return  (
      & lt;  div  & gt; 
    {/ * ref object is bound to input element * /}
     & lt;  input   type  =  "text"   ref  =  {ref}  / & gt; 
     & lt;/  div  & gt;  
    );
    });
     copy code   

    We bind the ref object to the input element so that we can use ref.current in the parent component to access the instance of the input element.

       const   ParentComponent  = ( ) = & gt; {
     const  inputRef =  useRef  ( null )
    
     const   handleClick  = ( ) = & gt; {
    InputRef.  current .  focus  ();  / / focus the subcomponent input element 
    }
    
     / / render the child component and pass the ref object to it 
     return  (
      & lt;  div  & gt; 
     & lt;  ChildComponent   ref  =  {inputRef}  / & gt; 
     & lt;  button   onClick  =  {handleClick}  & gt;  Focus input  & lt;/  button  & gt; 
     & lt;/  div  & gt;  
    );
    }
     copy code   

    We use the useRef method to create a ref object inputRef and pass it to the child component ChildComponent . Then, in the handleClick function, we use the inputRef.current.focus () method to focus the input element.

combined with the useRef method, we can easily access the DOM element of the ref object in the subcomponent through the above two steps.

in addition, we often use forwardRef API when writing high-level components (Higher-Order Component,HOC). A high-order component is a function that takes a component as an argument and returns a new component. forwardRef can help us ensure that ref is correctly passed to the wrapped component.

// High-level component withWrapper takes a component WrappedComponent as a parameter and returns a new component wrapped by forwardRef
function withWrapper(WrappedComponent) {
  return forwardRef((props, ref) => {
    return (
      <div ref={ref}>
        <WrappedComponent {...props} />
      </div>
    );
  });
}

const ChildComponent = ({ text }) => {
  return <div>{text}</div>;
};

const ParentComponent = () => {
  const wrapperRef = useRef(null);

  useEffect(() => {
    console.log(wrapperRef.current); // <div>...</div>
  }, []);

  // pass the subcomponent ChildComponent as an argument to the higher-order function withWrapper, and return a newly built WrappedChildComponent
  const WrappedChildComponent = withWrapper(ChildComponent);

  // render the new component returned by the higher-level component and pass the ref object wrapperRef as an attribute to the newly built WrappedChildComponent
  return (
    <div>
      <WrappedChildComponent ref={wrapperRef} text="Hello, world!" />
    </div>
  );
};

in the above example, we defined a high-order component named withWrapper , which takes a component as an argument and returns a new component. The new component will be wrapped in a div element, and a reference to this div element will be passed to the wrapped component as ref .

in the ParentComponent parent component, we use the withWrapper high-order function to create a new component WrappedChildComponent and pass its reference to wrapperRef . In this way, when ParentComponent is rendered, we can access the div element in the higher-order function through the wrapperRef object in the useEffect hook function, thus performing some operations.

Application scenario

combined with the above example, it is not difficult to find that forwardRef API is usually suitable for the following two scenarios:

  1. access the DOM node of the child component through the ref object;
  2. use forwardRef in high-level components.

can also be used in component libraries. For example, the Modal component in antd provides ref access.

from this we know that by using forwardRef , we can easily pass the ref object to the child component, so that we can access the instance of the child component or the DOM node and perform some operations.

Summary

briefly review this article on the role and usage of forwardRef API in React:

forwardRef in

React is a very important API because it can help us deal with special scenarios, such as the DOM node that accesses child components mentioned in this article or is used to write high-level components. By using forwardRef API, we can operate React components more conveniently and greatly improve our development efficiency. Therefore, it is necessary to master forwardRef in React. It will be very tedious if you don't understand the API, such as the need to access the subcomponent DOM node, through callback functions, and so on.

so, have you learned forwardRef ? welcome to leave a message below for discussion.

Exit mobile version