🔀
Integration with routing libs
Like react-router or Next.js file system based route.
Depending of the framework or routing library you are using, links between pages are not handled the same way.
Usually, you'll have a
<Link />
component provided by your routing library of choice. You need to let react-dsfr
knows about it so that whenever a link is needed in a DSFR component, you can provide the correct props for you <Link />
component.When registering your Link component, its props type will propagate to the react-dsfr API.
react-router
Next.js
Next.js AppDir
type-route
other
Warning: I do not recommend using react-router for any new project, consider using type-route, TanStack Router or any other type safe routing solution.
import React from "react";
import ReactDOM from "react-dom/client";
import { startReactDsfr } from "@codegouvfr/react-dsfr/cra";
import { Link } from "react-router-dom";
startReactDsfr({
defaultColorScheme: "system",
Link
});
//Only in TypeScript projects
declare module "@codegouvfr/react-dsfr/spa" {
interface RegisterLink {
Link: typeof Link;
}
}
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
{/* ... */}
</React.StrictMode>
);
Notice that everywhere a
linkProps
is asked you are now expected to provide an object with a to
property because react-router
's<Link />
component expects a to
prop instead of the typical href.pages/_app.tsx
import type { AppProps } from "next/app";
import { fr } from "@codegouvfr/react-dsfr";
import { createNextDsfrIntegrationApi } from "@codegouvfr/react-dsfr/next-pagesdir";
import Link from "next/link";
// Only in TypeScript projects
declare module "@codegouvfr/react-dsfr/next-pagesdir" {
interface RegisterLink {
Link: typeof Link;
}
}
const {
withDsfr,
dsfrDocumentApi
} = createNextDsfrIntegrationApi({
defaultColorScheme: "system",
Link
});
export { dsfrDocumentApi };
function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
export default withDsfr(App);
app/StartDsfr.tsx
"use client";
import { startReactDsfr } from "@codegouvfr/react-dsfr/next-appdir";
import { defaultColorScheme } from "./defaultColorScheme";
import Link from "next/link";
declare module "@codegouvfr/react-dsfr/next-appdir" {
interface RegisterLink {
Link: typeof Link;
}
}
startReactDsfr({
defaultColorScheme,
Link
});
export default function StartDsfr(){
//Yes, leave null here.
return null;
}
type-route unlike most routing library doesn't export a
<Link />
component <a />
are used directly.In consequence there isn't anything to setup.
You should be able to infer what needs to be done refering to the
react-router
instructions.If the library you are using doesn't export a
<Link />
(like type-route
for example) component, there isn't anything to do.Last modified 2mo ago