English

Poradnik · MUI (Material UI) · React

MUI 7 w praktyce – motyw, tryb ciemny, własne komponenty i DataGrid bez „domyślnego Materiala”

Budujemy panel kuchni pierogarni w Material UI 7 – tokeny projektowe i motyw ze zmiennymi CSS, tryb ciemny bez migotania, własne komponenty i warianty, DataGrid po stronie klienta i serwera, formularz z react-hook-form i Zod. Kod działa też na MUI 9.

Autor · · 22 min czytania

MUI to najpopularniejsza biblioteka komponentów dla Reacta, ale ma jedną wadę wizerunkową: aplikacje zbudowane „na domyślnych ustawieniach” wyglądają identycznie – niebieski pasek, wielkie litery na przyciskach, cienie pod każdą kartą. W tym poradniku zbudujesz panel kuchni pierogarni, który korzysta z całej mocy MUI (dostępność, gotowe komponenty, DataGrid), ale wygląda jak produkt z własnym systemem projektowym.

Wymagania wstępne: React z hookami i TypeScript na poziomie poradnika TypeScript. Przyda się znajomość react-hook-form i TanStack Query z poradnika React, ale nie jest konieczna.

7 → 9
wersje MUI – ten sam kod działa na obu
3
tryby kolorów – jasny, ciemny, systemowy
240
wierszy w DataGrid – sortowanie, filtry i akcje bez własnego kodu
1
plik z tokenami – cała marka w jednym miejscu

Krok 1. Instalacja

npm create vite@latest pierogi-admin -- --template react-ts
cd pierogi-admin
npm install @mui/material @mui/icons-material @emotion/react @emotion/styled @mui/x-data-grid @fontsource-variable/inter
npm install react-hook-form @hookform/resolvers zod @tanstack/react-query

MUI używa Emotion jako silnika stylów, stąd dwa pakiety @emotion/*. Font Inter instalujesz lokalnie przez Fontsource – bez zapytań do Google Fonts i bez skoku układu po doczytaniu fontu z sieci.

Konfiguracja projektu

package.json
{
  "name": "pierogi-admin-mui",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@emotion/react": "^11.14.0",
    "@emotion/styled": "^11.14.1",
    "@fontsource-variable/inter": "^5.3.0",
    "@hookform/resolvers": "^7.0.9",
    "@mui/icons-material": "^7.3.11",
    "@mui/material": "^7.3.11",
    "@mui/x-data-grid": "^9.18.0",
    "@tanstack/react-query": "^5.108.4",
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "react-hook-form": "^7.92.0",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/react": "^19.3.0",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client"],
    "jsx": "react-jsx",
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true
  },
  "include": ["src", "vite.config.ts"]
}
vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [react()],
});
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogarnia · Kitchen admin</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

Krok 2. Tokeny projektowe i motyw

Tokeny projektowe (design tokens) to nazwane decyzje: „kolor marki 700”, „promień średni”, „font bezszeryfowy”. Motyw MUI jest tylko jednym z ich odbiorców – te same tokeny możesz wyeksportować do e-maili, wykresów czy aplikacji mobilnej.

Diagram: Od tokenów do komponentów: jedno źródło decyzji, zero kolorów wpisanych w komponenty

Trzy pliki motywu: tokeny, deklaracje typów (augmentacja modułu) i sam motyw:

Tokeny, typy i motyw

src/theme/tokens.ts
// Design tokens: the single source of brand decisions. The MUI theme only maps them.
export const tokens = {
  font: {
    sans: '"Inter Variable", system-ui, -apple-system, "Segoe UI", sans-serif',
  },
  radius: { sm: 6, md: 10, lg: 14 },
  // "Beetroot" brand scale instead of the default Material blue.
  brand: { 50: "#fff0f6", 100: "#ffdeeb", 300: "#faa2c1", 500: "#e64980", 700: "#c2255c", 900: "#a61e4d" },
  neutral: {
    0: "#ffffff", 50: "#f8f9fa", 100: "#f1f3f5", 200: "#e9ecef", 300: "#dee2e6",
    500: "#868e96", 700: "#495057", 800: "#2b2f36", 900: "#1d2026", 950: "#141619",
  },
  status: {
    light: { placed: "#1971c2", cooking: "#d9480f", delivering: "#6741d9", delivered: "#2b8a3e", cancelled: "#868e96" },
    dark: { placed: "#74c0fc", cooking: "#ffa94d", delivering: "#b197fc", delivered: "#8ce99a", cancelled: "#adb5bd" },
  },
} as const;

export type OrderStatus = keyof typeof tokens.status.light;
src/theme/mui.d.ts
import type { OrderStatus } from "./tokens.ts";

// Module augmentation: teach MUI's types about our custom theme parts.
declare module "@mui/material/styles" {
  // We always enable CSS variables, so `theme.vars` is never undefined.
  interface CssThemeVariables {
    enabled: true;
  }
  interface Palette {
    status: Record<OrderStatus, string>;
  }
  interface PaletteOptions {
    status?: Record<OrderStatus, string>;
  }
}

declare module "@mui/material/Button" {
  interface ButtonPropsVariantOverrides {
    soft: true;
  }
}
src/theme/theme.ts
import { createTheme } from "@mui/material/styles";
import { tokens } from "./tokens.ts";

const { brand, neutral, radius, status } = tokens;

export const theme = createTheme({
  // CSS variables + a class on <html> switch light/dark without re-rendering React.
  cssVariables: { colorSchemeSelector: "class" },
  colorSchemes: {
    light: {
      palette: {
        primary: { main: brand[700], light: brand[500], dark: brand[900], contrastText: "#fff" },
        background: { default: neutral[50], paper: neutral[0] },
        text: { primary: neutral[900], secondary: neutral[700] },
        divider: neutral[200],
        status: status.light,
      },
    },
    dark: {
      palette: {
        primary: { main: brand[300], light: brand[100], dark: brand[500], contrastText: neutral[950] },
        background: { default: neutral[950], paper: neutral[900] },
        text: { primary: neutral[100], secondary: neutral[500] },
        divider: "rgba(255, 255, 255, 0.10)",
        status: status.dark,
      },
    },
  },
  shape: { borderRadius: radius.md },
  typography: {
    fontFamily: tokens.font.sans,
    h1: { fontSize: "1.75rem", fontWeight: 700, letterSpacing: "-0.02em" },
    h2: { fontSize: "1.25rem", fontWeight: 650, letterSpacing: "-0.01em" },
    overline: { fontWeight: 600, letterSpacing: "0.06em" },
    button: { textTransform: "none", fontWeight: 600 }, // no SHOUTING buttons
  },
  components: {
    MuiButtonBase: { defaultProps: { disableRipple: true } },
    MuiButton: {
      defaultProps: { disableElevation: true },
      styleOverrides: {
        root: ({ theme }) => ({
          borderRadius: radius.sm,
          "&.Mui-focusVisible": { outline: `2px solid ${theme.vars.palette.primary.main}`, outlineOffset: 2 },
          // Custom variant registered in mui.d.ts: <Button variant="soft">
          variants: [
            {
              props: { variant: "soft" },
              style: {
                color: theme.vars.palette.primary.main,
                backgroundColor: theme.alpha(theme.vars.palette.primary.main, 0.12),
                "&:hover": { backgroundColor: theme.alpha(theme.vars.palette.primary.main, 0.2) },
              },
            },
          ],
        }),
      },
    },
    MuiPaper: { defaultProps: { elevation: 0 }, styleOverrides: { root: { backgroundImage: "none" } } },
    MuiCard: { defaultProps: { variant: "outlined" } },
    MuiAppBar: {
      defaultProps: { elevation: 0, color: "inherit", position: "sticky" },
      styleOverrides: { root: ({ theme }) => ({ borderBottom: `1px solid ${theme.vars.palette.divider}` }) },
    },
    MuiTextField: { defaultProps: { size: "small", fullWidth: true } },
    MuiChip: { styleOverrides: { root: { fontWeight: 600, borderRadius: radius.sm } } },
    MuiTooltip: { defaultProps: { arrow: true } },
  },
});

Co tu się dzieje:

  • cssVariables: { colorSchemeSelector: "class" } – MUI generuje zmienne CSS (--mui-palette-primary-main) i przełącza schemat klasą .dark na <html>. Komponenty odwołują się do zmiennych, więc zmiana trybu to tylko zmiana klasy, bez ponownego renderowania drzewa Reacta.
  • colorSchemes.light / colorSchemes.dark – dwa zestawy palet z tych samych tokenów. W trybie ciemnym kolor główny jest jaśniejszy (brand[300]), żeby zachować kontrast.
  • theme.vars.palette… w nadpisaniach zamiast theme.palette… – wartość zmiennej CSS, a nie stały kolor jasnego motywu. Dzięki augmentacji CssThemeVariables { enabled: true } TypeScript wie, że theme.vars zawsze istnieje.
  • components – domyślne propsy i nadpisania stylów dla wszystkich instancji komponentu. To tu znikają cienie, ripple i wielkie litery.
  • Własny wariant soft – rejestrujesz go w ButtonPropsVariantOverrides, a styl dodajesz w styleOverrides.root.variants. Od tej chwili <Button variant="soft"> jest typowany i podpowiadany w edytorze.
Domyślny MUIW tym projekcieGdzie
niebieski #1976d2„buraczkowa” skala marki z tokenówcolorSchemes.*.palette.primary
RobotoInter Variable z Fontsourcetypography.fontFamily
BUTTON wielkimi literamitextTransform: "none", waga 600typography.button
cienie (elevation 1–24)obramowania 1 px, elevation: 0MuiPaper, MuiCard, MuiAppBar
fala ripple po kliknięciuwyraźny focus ring 2 pxMuiButtonBase, MuiButton
pola mediumpola small – gęstszy panelMuiTextField.defaultProps

Krok 3. Tryb ciemny bez migotania

Z motywem ze zmiennymi CSS tryb ciemny wymaga trzech rzeczy: ThemeProvider z defaultMode, CssBaseline enableColorScheme (paski przewijania i natywne pola też ciemnieją) oraz przełącznika opartego na useColorScheme().

Przełącznik trybu kolorów

src/components/ThemeModeToggle.tsx
import DarkModeOutlined from "@mui/icons-material/DarkModeOutlined";
import LightModeOutlined from "@mui/icons-material/LightModeOutlined";
import SettingsBrightnessOutlined from "@mui/icons-material/SettingsBrightnessOutlined";
import ToggleButton from "@mui/material/ToggleButton";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";
import { useColorScheme } from "@mui/material/styles";

export function ThemeModeToggle() {
  const { mode, setMode } = useColorScheme(); // "light" | "dark" | "system", persisted in localStorage
  if (!mode) return null; // not resolved yet on the very first render

  return (
    <ToggleButtonGroup
      size="small"
      exclusive
      value={mode}
      onChange={(_, next: typeof mode | null) => next && setMode(next)}
      aria-label="Colour scheme"
    >
      <ToggleButton value="light" aria-label="Light">
        <LightModeOutlined fontSize="small" />
      </ToggleButton>
      <ToggleButton value="system" aria-label="System">
        <SettingsBrightnessOutlined fontSize="small" />
      </ToggleButton>
      <ToggleButton value="dark" aria-label="Dark">
        <DarkModeOutlined fontSize="small" />
      </ToggleButton>
    </ToggleButtonGroup>
  );
}

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Krok 4. Własne komponenty: styled, sx i paleta statusów
  • Krok 5. DataGrid: tabela po stronie klienta i serwera
  • Krok 6. Formularz: react-hook-form + komponenty MUI
  • Krok 7. Składamy panel
  • Jak uniknąć „domyślnego Materiala” – lista kontrolna
  • Typowe błędy
  • Sprawdź się
  • Co dalej

Załóż darmowe konto · Zaloguj się