Skip to content

Instantly share code, notes, and snippets.

@ColmBhandal
Last active August 8, 2022 20:49
Show Gist options
  • Save ColmBhandal/8d31fe2d1076f00e606c7c560319c957 to your computer and use it in GitHub Desktop.
Save ColmBhandal/8d31fe2d1076f00e606c7c560319c957 to your computer and use it in GitHub Desktop.
Typescript Version of AndreasBBS's React Router Decorator

Original solution thanks to AndreasBBS here.

// This file goes in your .storybook folder
import ReactRouterDecorator from "./ReactRouterDecorator"
// You can add more decorators to the list
export const decorators = [ReactRouterDecorator];
// Other stuff here
// You can put this file anywhere. This Gist assumed it's in the .storybook folder
import React, { useEffect } from 'react'
import { action } from '@storybook/addon-actions'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { Args, ReactFramework } from '@storybook/react'
import { DecoratorFunction } from '@storybook/csf'
const LocationChangeAction = ({children}) => {
const location = useLocation()
useEffect(() => {
if(location.key !== "default")
action('React Router Location Change')(location)
}, [location])
return <>{children}</>
}
const ReactRouterDecorator: DecoratorFunction<ReactFramework, Args> = (Story, context) => {
return (
<MemoryRouter>
<LocationChangeAction>
<Story {...context}/>
</LocationChangeAction>
</MemoryRouter>
)
}
export default ReactRouterDecorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment