🤝MUI integration

Use MUI components in your App or DSFRify your website build with MUI.

react-dsfr features a DSFR theme for MUI. This enables you to use the large library of MUI components in your website, they will blend in nicely.

First of all you'll have to remove all usage of <ThemeProvider /> and createTheme() from your codebase (if any) then implement the following approach:

import MuiDsfrThemeProvider from "@codegouvfr/react-dsfr/mui";

function App() {

    return (
        <MuiDsfrThemeProvider>
            {/* your app ... */}
        </MuiDsfrThemeProvider>
    );
}
Custom variable in MUI theme

If you have custom variables in your MUI theme implement the following approach.

In this example we have augmented the MUI theme so it was possible to call theme.custom.isDarkModeEnabled.

import { createMuiDsfrThemeProvider } from "@codegouvfr/react-dsfr/mui";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
import type { Theme } from "@mui/material/styles";

declare module "@mui/material/styles" {

    interface Theme {
        custom: {
            isDarkModeEnabled: boolean;
        }
    }
}

const { MuiDsfrThemeProvider } = createMuiDsfrThemeProvider({
    "augmentMuiTheme": ({ nonAugmentedMuiTheme, frColorTheme }) => ({
        ...nonAugmentedMuiTheme,
        "custom": {
            "isDarkModeEnabled": frColorTheme.isDark
        }
    })
});

function App() {

    return (
        <MuiDsfrThemeProvider>
            {/* your app ... */}
        </MuiDsfrThemeProvider>
    );
}

The demo setups for Vite, Next ans create-react-app all commes with MUI already setup. You can find aditional informations about this tool here:

Next.js: Improving first print

In Next.js setup, on initial page load you may experience a few frames where MUI components aren't aware that the dark mode is enabled.

You can eradicate these few frames on subsequent page load by telling Next.js to perform SSR in the correct color scheme for the user:

_app.tsx
const { withDsfr, dsfrDocumentApi } = createNextDsfrIntegrationApi({
  defaultColorScheme: 'system',
  doPersistDarkModePreferenceWithCookie: true
});

Be aware: this will opt you out from Automatic Static Optimization, every hit of your website will trigger a complete render on the backend, so it probably isn't worth it unless you have already opted out from static optimization.

Setting up Next.js + MUI + react-dsfr

Be aware that the API have changed since this video was recorded.

All demo setup are preconfigured with MUI installed. \

Last updated

Logo

2022-2023 Pôle logiciel libre d'Etalab - MIT license