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)