Skip to content

Instantly share code, notes, and snippets.

@abenevaut
Last active June 19, 2024 19:38
Show Gist options
  • Save abenevaut/c403b864bcb3ab03a2efca4456028fb1 to your computer and use it in GitHub Desktop.
Save abenevaut/c403b864bcb3ab03a2efca4456028fb1 to your computer and use it in GitHub Desktop.
  • app.jsx - load router from attached project router file

  • router.jsx - load project router

  • ReactRouterProvider.jsx - the dedicated react-router router; could be cloned for inertia and others react/next routers

  • RouterContext.jsx - the abstract router

  • Link.jsx - the Link component

  • (Not tested) InertiaRouterProvider.jsx - the dedicated inertiajs router

'use client'
import React from 'react'
import ReactDOM from 'react-dom/client'
import { Router } from "./router.jsx";
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Router />
</React.StrictMode>,
)
'use client'
import { InertiaApp } from '@inertiajs/inertia-react';
import { RouterProvider } from '../Contexts/RouterContext';
const InertiaProvider = ({ initialPage, resolveComponent }) => {
const routerValue = {
navigate: (path) => Inertia.visit(path),
};
return (
<RouterProvider value={routerValue}>
<InertiaApp initialPage={initialPage} resolveComponent={resolveComponent} />
</RouterProvider>
);
};
export default InertiaProvider;
'use client'
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { RouterProvider } from '../Contexts/RouterContext';
const ReactRouterProvider = ({ routes }) => {
const routerValue = {
navigate: (path) => {},
};
return (
<Router>
<RouterProvider value={routerValue}>
<Routes>
{routes.map((route, index) => (
<Route key={index} path={route.path} element={route.element} />
))}
</Routes>
</RouterProvider>
</Router>
);
};
export default ReactRouterProvider;
'use client'
import ReactRouterProvider from "./Providers/ReactRouterProvider.jsx";
import Home from './Pages/Home.jsx'
const routes = [{
path: "/",
name: 'home',
element: <Home />,
}];
Router.propTypes = {};
export function Router() {
return (<ReactRouterProvider routes={routes} />)
}
'use client'
import { createContext, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
const RouterContext = createContext();
export const RouterProvider = ({ children }) => {
const navigate = useNavigate();
const routerValue = {
navigate: (path) => navigate(path),
};
return (
<RouterContext.Provider value={routerValue}>
{children}
</RouterContext.Provider>
);
};
export const useRouter = () => useContext(RouterContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment