Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

next/router: Cannot read property 'pathname' of null (storybook)

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?

like image 619
sinnerwithguts Avatar asked Oct 11 '25 20:10

sinnerwithguts


1 Answers

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",
  ],
};
like image 72
GeorgeButter Avatar answered Oct 14 '25 22:10

GeorgeButter