36
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

NextLinkでComponentを囲ったら、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 Link.のエラーがでた

Posted at

個人の備忘録です。

環境

  • react: 17.0.2
  • react-hook-form: 7.28.0
  • next: 11.1.3
  • chakra-ui: 1.8.5

やりたいこと

  • chakra-ui の Link を component 化してラップして使いたい

エラーの再現

component
export const LinkComponent = ({ children, ...props }: LinkProps) => {
  return (
    <Link _focus={{ boxShadow: 'none' }} {...props}>
      {children}
    </Link>
  );
};
使用側
import NextLink from 'next/link';

<NextLink href={'/hoge'} passHref>
  <LinkComponent>一覧に戻る</MwLink>
</NextLink>

調査

公式

Linkの子がfunctional componentの場合、passHrefの使用に加えて、React.forwardRefでコンポーネントをラップする必要があります。

やったこと

  • ref を使う
  • ただ、以下の記述だと別のエラーが出る
import { forwardRef, LegacyRef } from 'react';
import { Link, LinkProps } from '@chakra-ui/react';

export const LinkComponent = forwardRef(function MwLinkFunction(
  { children, ...props }: LinkProps,
  ref
) {
  return (
    <Link
      _focus={{ boxShadow: 'none' }}
      {...props}
      ref={ref as LegacyRef<HTMLAnchorElement>}
    >
      {children}
    </Link>
  );
});
error
Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
at SearchSpecialistContainer

解決方法

  • 以下で今までのエラーが出なくなった
import { Link, LinkProps } from '@chakra-ui/react';
import { forwardRef } from 'react';

const LinkComponent = forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => {
  const { children, ...linkProps } = props;
  return (
    <Link _focus={{ boxShadow: 'none' }} {...linkProps} ref={ref}>
      <>{children}</>
    </Link>
  );
});

LinkComponent.displayName = 'LinkComponent';
export default LinkComponent;
36
43
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?