📀

Remix × Storybook: Error: useHref() may be used only in the context ...

This article was automatically translated from theJapanese original by AI. It may contain translation errors.

This post was published over 1 year ago. Its content may be outdated.

How to fix Error: useHref() may be used only in the context of a <Router> component. when trying to display a component in Storybook in a project that uses Remix


An error occurred when trying to display Remix’s Link component in Storybook.

Solution

As discussed on GitHub, edit the code in .storybook/preview.tsx as follows.

Note: I’m using Chakra UI, so ChakraProvider is included. If you’re not using it, remove the Chakra parts before using this.

import type { Preview } from "@storybook/react";
import { ChakraProvider, Theme } from "@chakra-ui/react";
import { defaultSystem } from "@chakra-ui/react";
import React from "react";
import { createRemixStub } from "@remix-run/testing";
 
const preview: Preview = {
  decorators: [
    (Story) => {
      const RemixStub = createRemixStub([
        {
          path: "/*",
          action: () => ({ redirect: "/" }),
          loader: () => ({ redirect: "/" }),
          Component() {
            return <Story />;
          },
        },
      ]);
      return (
        <ChakraProvider
          children={
            <Theme appearance="light">
              <RemixStub />
            </Theme>
          }
          value={defaultSystem}
        />
      );
    },
  ],
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/i,
      },
    },
  },
};
 
export default preview;

The key point is import { createRemixStub } from "@remix-run/testing";.
On GitHub it’s written as import { unstable_createRemixStub as createRemixStub } from '@remix-run/testing';, but it seems it’s no longer unstable recently, so you can drop the unstable_.

By the way

As noted here, there’s also the opinion that components you view in Storybook shouldn’t depend on a framework like Remix in the first place.

Recent Articles

Network(beta)

Drag to move / Ctrl+wheel to zoom