Friday, July 27, 2018

ref Forwarding in React 16.3

When we create nested components in react, react does not allow accessing the DOM of the inner element through refs, The ref on the wrapper component points to the wrapper component and not the inner component. In some cases we might need to access the inner component through refs, react 16.3 provides a way to achieve this using ref Forwarding.


ref Forwarding is a way in which a component can take a ref parameter and pass it on to its child/nested component. To do this we need to create a React ref by calling React.createRef, pass the ref to the wrapper component as a parameter and then forward the ref to the child / nested component. When the ref is attached, ref.current will point to the child/nested components DOM node.

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

Search Flipkart Products:
Flipkart.com

No comments: