The easiest way to define full typesafe router in React.js. just 3 api you need to use. and the vue3 version is also available here (https://github.com/qinjialei24/vue-typesafe-router).
npm i react-typesafe-router
#or
pnpm i react-typesafe-router
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import {
createTypesafeRoute,
useTypesafeNavigate,
useTypesafeQuery,
} from "react-typesafe-router";
const barTypesafeRoute = createTypesafeRoute<{ name: string; age?: number }>({
path: "/bar",
element: <Bar />,
});
const fooTypesafeRoute = createTypesafeRoute<{ name: string; age?: number }>({
path: "/foo",
element: <Foo />,
});
const router = createBrowserRouter([
{
path: "/",
element: <Foo />,
},
fooTypesafeRoute,
barTypesafeRoute,
]);
import { useTypesafeNavigate } from "react-typesafe-router";
function Foo() {
const navigateToBar = useTypesafeNavigate(barTypesafeRoute);
return (
<div>
<h3>Hello Foo!</h3>
<button onClick={() => navigateToBar({ name: "jack" })}>Go to Bar</button>
</div>
);
}
Now, You can pass route query data with full typesafe!
import { useTypesafeNavigate, useTypesafeQuery } from "react-typesafe-router";
function Bar() {
const barQuery = useTypesafeQuery(barTypesafeRoute);
const navigateToFoo = useTypesafeNavigate(fooTypesafeRoute);
return (
<div>
<h3>Hello Bar!</h3>
<h3>name: {barQuery.name}</h3>
<h3>age: {barQuery.age}</h3>
<button onClick={() => navigateToFoo({ name: "jack" })}>Go to Foo</button>
</div>
);
}