Theme toggling (light/dark mode) is a widely used feature on websites. Let's implement it using MobX in React! π
1οΈβ£ Install MobX in Your React Project
If you haven't installed MobX yet, run:
npm install mobx mobx-react-lite
2οΈβ£ Create a MobX Store for Theme
π Create a new file: store/ThemeStore.js
import { makeAutoObservable } from "mobx";
class ThemeStore {
theme = "light"; // Observable state
constructor() {
makeAutoObservable(this);
}
toggleTheme() {
this.theme = this.theme === "light" ? "dark" : "light"; // Action
}
}
const themeStore = new ThemeStore();
export default themeStore;
πΉ Explanation:
-
theme
: Observable state (tracks whether it's "light" or "dark"). -
toggleTheme()
: Action to switch the theme. -
makeAutoObservable(this)
: Makes everything automatically observable.
3οΈβ£ Use the Store in a React Component
π Modify App.js
to use MobX and React.
import React from "react";
import { observer } from "mobx-react-lite";
import themeStore from "./store/ThemeStore";
const ThemeSwitcher = observer(() => {
return (
<div
style={{
height: "100vh",
display: "flex",
justifyContent: "center",
alignItems: "center",
background: themeStore.theme === "light" ? "#fff" : "#333",
color: themeStore.theme === "light" ? "#000" : "#fff",
}}
>
<button onClick={() => themeStore.toggleTheme()}>
Switch to {themeStore.theme === "light" ? "Dark" : "Light"} Mode
</button>
</div>
);
});
export default ThemeSwitcher;
πΉ What's Happening?
-
observer()
: Ensures the component re-renders whenthemeStore.theme
changes. - Button switches between light and dark themes dynamically.
4οΈβ£ Render the Theme Switcher
π Modify main.jsx
(Vite) or index.js
(CRA).
import React from "react";
import ReactDOM from "react-dom/client";
import ThemeSwitcher from "./App";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<ThemeSwitcher />
</React.StrictMode>
);
π Run the App!
npm start
Click the button and see the theme switch instantly! π
Top comments (0)