Created
August 26, 2024 13:56
-
-
Save jgcmarins/a591824edcff18910490cb8513a2575c to your computer and use it in GitHub Desktop.
router abstraction to work on both Next.js Apps and React Apps with react-router-dom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable react-hooks/rules-of-hooks */ | |
// 24:33 error React Hook "useNextRouter" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks | |
// 25:43 error React Hook "useReactRouterNavigate" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks | |
// 43:35 error React Hook "useNextPathname" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks | |
// 44:37 error React Hook "useReactRouterLocation" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks | |
'use client'; | |
import { usePathname as useNextPathname, useRouter as useNextRouter } from 'next/navigation'; | |
import { | |
useLocation as useReactRouterLocation, | |
useNavigate as useReactRouterNavigate, | |
} from 'react-router-dom'; | |
type NavigationFunction = (path: string) => void; | |
function useIsNextJs() { | |
return typeof useNextRouter === 'function' && typeof useNextPathname === 'function'; | |
} | |
export function useNavigateRouter(): NavigationFunction { | |
const isNextJs = useIsNextJs(); | |
const nextRouter = isNextJs ? useNextRouter() : null; | |
const reactRouterNavigate = !isNextJs ? useReactRouterNavigate() : null; | |
return (path: string) => { | |
if (isNextJs && nextRouter) { | |
nextRouter.push(path); | |
return; | |
} | |
if (reactRouterNavigate) { | |
reactRouterNavigate(path); | |
return; | |
} | |
}; | |
} | |
export function useLocationPathname(): string { | |
const isNextJs = useIsNextJs(); | |
const nextPathname = isNextJs ? useNextPathname() : ''; | |
const reactLocation = !isNextJs ? useReactRouterLocation() : null; | |
return isNextJs ? nextPathname : reactLocation?.pathname || ''; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://twitter.com/jgcmarins/status/1828071642074943673