Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 427
bakrall Avatar asked Oct 14 '22 22:10

bakrall


1 Answers

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.

like image 188
Linda Paiste Avatar answered Oct 18 '22 23:10

Linda Paiste