storybook-router icon indicating copy to clipboard operation
storybook-router copied to clipboard

React Router 6 Support

Open jeremytenjo opened this issue 4 years ago • 5 comments

Issue:

Renders blank when using "react-router-dom": "^6.0.0-alpha.4",

jeremytenjo avatar May 10 '20 22:05 jeremytenjo

would love this

sgioia9 avatar Jul 22 '20 15:07 sgioia9

With 6.0.0 I get:

A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

FTWinston avatar Nov 05 '21 16:11 FTWinston

Came across this myself but with React Router 6 this package is no longer needed, you can just use the new MemoryRouter in a decorator:

preview.js

import { MemoryRouter } from 'react-router-dom';

export const decorators = [
  (Story) => (
    <MemoryRouter>
      <Story />
    </MemoryRouter>
  )
];

madeleineostoja avatar Nov 06 '21 05:11 madeleineostoja

Oh that's simpler than what I came up with. Thanks!

FTWinston avatar Nov 07 '21 15:11 FTWinston

Just in case someone comes looking to keep the Action trigger on location change I added this Wrapper to mine and is working pretty well:

import React, { useEffect } from 'react'
import { action } from '@storybook/addon-actions'
import { BrowserRouter, useLocation } from 'react-router-dom'

const LocationChangeAction = ({children}) => {
  const location = useLocation()

  useEffect(() => {
    if(location.key !== "default")
      action('React Router Location Change')(location)
  }, [location])

  return <>{children}</>
}

export default function ReactRouterDecorator(Story, context) {
  return (
    <BrowserRouter>
      <LocationChangeAction>
        <Story {...context}/>
      </LocationChangeAction>
    </BrowserRouter>
  )
}

NOTE: It was also working with the MemoryRouter but you get a default action trigger on story render for the path "/", the trigger I'm avoiding with my if condition.

AndreasBBS avatar Feb 03 '22 03:02 AndreasBBS

@AndreasBBS Very cool, thank you! I've added a couple of types and created a Typescript version here.

ColmBhandal avatar Aug 08 '22 17:08 ColmBhandal