суббота, 25 февраля 2023 г.

What are forward refs in React?

 In React, forward refs refer to a technique used to pass a ref from a parent component to a child component that can be used to access the child's DOM node or instance. This is useful when you need to access the child component's methods or properties from the parent component or from another component.


Forward refs were introduced in React version 16.3 as a way to solve the problem of accessing child component instances when using higher-order components (HOCs) or when rendering a component using a function instead of a class.

To create a forward ref in React, you use the React.forwardRef function, which creates a new component that accepts a ref object as a prop and forwards it to the child component.

Here is an example of a parent component passing a ref to a child component using forward refs:

const ChildComponent = React.forwardRef((props, ref) => {

  return (

    <div ref={ref}>

      // Child component code

    </div>

  );

});


const ParentComponent = () => {

  const childRef = React.useRef();


  const handleClick = () => {

    console.log(childRef.current);

  }


  return (

    <div>

      <ChildComponent ref={childRef} />

      <button onClick={handleClick}>Log child node</button>

    </div>

  );

};


In this example, the ChildComponent is defined using React.forwardRef to create a new component that accepts a ref. The ParentComponent passes a ref to the ChildComponent using the ref prop, and can access the child component's DOM node by calling childRef.current.

Комментариев нет:

Отправить комментарий