If you want to dynamically switch the App Theme in a React-Admin app using Redux or another global store, you must integrate a custom theme provider with React-Admin’s <Admin> component and sync it with your state logic.
Step‑by‑Step Guide
Implement a seamless light/dark theme toggle in your React-Admin app using MUI, Redux, and a custom UI control step by step.
Step 1: Define Your Themes
Create reusable MUI theme objects to represent the light and dark versions of your app.
// themes.jsimport { createTheme } from "@mui/material/styles";
export const lightTheme = createTheme({
palette: {
mode: "light",
primary: { main: "#1976d2" },
},
});
export const darkTheme = createTheme({
palette: {
mode: "dark",
primary: { main: "#90caf9" },
},
});
Step 2: Add Theme Slice to Your Store
Create a slice to store and toggle the current theme mode (light or dark).
// themeSlice.js (Redux example)import { createSlice } from "@reduxjs/toolkit";
const initialState = {
mode: "light", // or "dark"
};
const themeSlice = createSlice({
name: "theme",
initialState,
reducers: {
toggleTheme: (state) => {
state.mode = state.mode === "light" ? "dark" : "light";
},
},
});
export const { toggleTheme } = themeSlice.actions;
export default themeSlice.reducer;
Step 3: Connect Admin to Store Theme
Fetch the current theme mode from the Redux store and pass the matching MUI theme to React-Admin.
// App.tsximport { Admin } from "react-admin";
import { useSelector } from "react-redux";
import { lightTheme, darkTheme } from "./themes";
const App = () => {
const themeMode = useSelector((state) => state.theme.mode);
const theme = themeMode === "dark" ? darkTheme : lightTheme;
return <Admin theme={theme} dataProvider={...} />;
};
export default App;
Also Read: How to Update ReactJS to the Latest Version Safely and Effectively
Step 4: Add a Theme Toggle UI
Create a UI control (e.g., icon button) that allows users to switch between light and dark themes by dispatching the toggle action.
// ThemeToggle.tsximport { useDispatch, useSelector } from "react-redux";
import { toggleTheme } from "./themeSlice";
import IconButton from "@mui/material/IconButton";
import Brightness4Icon from "@mui/icons-material/Brightness4";
const ThemeToggle = () => {
const dispatch = useDispatch();
const mode = useSelector((state) => state.theme.mode);
return (
<IconButton onClick={() => dispatch(toggleTheme())} color="inherit">
<Brightness4Icon />
</IconButton>
);
};
export default ThemeToggle;
Step 5: Place Toggle Button in Layout
Insert the toggle button into your app bar, sidebar, or a persistent header so it’s accessible across views.
// Example: Inside custom AppBarimport { AppBar } from "react-admin";
import ThemeToggle from "./ThemeToggle";
const MyAppBar = (props) => (
<AppBar {...props}>
<ThemeToggle />
</AppBar>
);