What does forwardRef by a component in React dev tools mean and how can I use it?
Asked Answered
E

1

8

When I inspect component structure in React dev tools, I can see that there is a forwardRef mark. I am perplexed because there is no sign of it being used in the source code. How is it that it is there and how can I use it?

enter image description here

Ensoul answered 9/2, 2021 at 9:19 Comment(1)
Probably you are using a library that internally uses forwardRef to give you access to the elements inside wrappers made by library. Provide some code to understand better.Attah
P
7

The forwardRef calls aren't in your own code, they are in the packages that you are using.

styled.button appears to be from styled-components. This package uses forwardRef to forward any ref that you set on your styled button component to the underlying button component. You can see it in their source code right here:

WrappedStyledComponent = ((React.forwardRef(forwardRef): any): IStyledComponent);

Usage of forwardRef began with styled-components v4 -- see step #2 on this migration guide:

Make sure your application is using react >= 16.3; internally we are using the new React.forwardRef API and new context APIs if you wish to try and polyfill for older React version support

It is also explained on this Tips and Tricks page:

Refs to DOM nodes

styled-components makes use of the new React 16.3 API forwardRef. Thus, set refs like you would on any other component and they will automatically resolve to the underlying DOM element or wrapped component class instance.

Palsy answered 15/4, 2021 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.