4

I have an app which uses Next.js and MaterialUI. In order for Link component to work properly with MaterialUI I have a special Link component that looks like this:

function Link(props) {
  const {
    href,
    activeClassName = 'active',
    className: classNameProps,
    innerRef,
    naked,
    prefetch,
    ...other
  } = props;

  const router = useRouter();
  const pathname = typeof href === 'string' ? href : href.pathname;
  const className = clsx(classNameProps, {
    [activeClassName]: router.pathname === pathname && activeClassName
  });

  if (naked) {
    return (
      <NextComposed
        className={className}
        ref={innerRef}
        href={href}
        prefetch={prefetch}
        {...other}
      />
    );
  }

  return (
    <MuiLink component={NextComposed} className={className} ref={innerRef} href={href} {...other} />
  );
}

This works absolutely fine when I need it. However, when I start adding my components (with this Link) to Storybook, I get an error:

Uncaught TypeError: Cannot read property 'pathname' of null
        at Link 

The example of Link usage in a component that I add to Storybook:

const MyComponent = (props) => (<Button
                    className={classes.loginButton}
                    disableRipple
                    edge="end"
                    variant="contained"
                    color="secondary"
                    component={Link}
                    naked
                    href="/login"
                  >
                    Login
                  </Button>)

When I try to console.log() router, I do get null which is weird. What am I doing wrong here?

sinnerwithguts
  • 573
  • 7
  • 20

2 Answers2

2

You can mock the behaviour of the next router by using the package storybook-addon-next-router. Using this package will not only make the router work but it will also give you the ability to customise the router values on a per story basis.

// .storybook/main.js
module.exports = {
  ...config,
  addons: [
    ...your addons
    "storybook-addon-next-router",
  ],
};
GeorgeButter
  • 2,521
  • 1
  • 29
  • 47
0

I came across the same issue when upgrading to Next v9.5. It looks like the Link component assumes that the Next router would be present.

This PR seems to fix the issue. Upgrading to the v9.5.1-canary.1 version resolved it for me.

Cian
  • 56
  • 1
  • 6