1

I want to wrap an OutboundLink component from the Gatsby Google Analytics plugin in a Material UI Link component.

I get this error message in the console:

index.js:2177 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `ForwardRef`.
    in OutboundLink (created by ForwardRef)
    in ForwardRef (created by ForwardRef(Typography))
    in ForwardRef(Typography) (created by WithStyles(ForwardRef(Typography)))
    in WithStyles(ForwardRef(Typography)) (created by ForwardRef(Link))
    in ForwardRef(Link) (created by WithStyles(ForwardRef(Link)))
    in WithStyles(ForwardRef(Link)) (created by OutboundLinkThemed)
    in OutboundLinkThemed (created by Credibility)
    in p (created by ForwardRef(Typography))
    in ForwardRef(Typography) (created by WithStyles(ForwardRef(Typography)))
    in WithStyles(ForwardRef(Typography)) (created by MyOwnComponent)
    ...

The Material UI documentation discusses this here and links to the React documentation on how to solve it.

I am at a loss on how to solve this.

I tried this solution which does not work since OutboundLink does not have an innerRef property.

I also tried this which still gives a warning:

import { Link as MuiLink } from "@material-ui/core";

const ForwardOutboundLink = React.forwardRef((props, ref) => (
  <OutboundLink {...props} ref={ref}>
));

export const OutboundLinkThemed = ({ href, target, rel, caption}) => {

  return (
    <MuiLink
      component={ForwardOutboundLink}
      href={href}
      target={target}
      rel={rel}
      underline="hover"
    >
        {caption}
    </MuiLink>
  );
};

So far the rendered components works as expected so I ignored it the last days. But I cannot keep on accumulate warnings within my app. How do I solve this?

EliteRaceElephant
  • 7,744
  • 4
  • 47
  • 62

1 Answers1

1

The following gets rid of the warning (using forwardRef, but not putting the ref on OutboundLink since it doesn't support it):

const ForwardOutboundLink = React.forwardRef((props, ref) => (
  <OutboundLink {...props} />
));

Edit OutboundLink forwardRef

The ideal solution would be to fix this in OutboundLink within the plugin so that it uses forwardRef and then specifies the ref on the a tag.

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198