Dark Mode
Quantum provides a built in dark theme which can be loaded and dynamically enabled in the browser. The @qtm/tokens
package contains the tokens-dark.css to use.
Usage
# with npm
npm install @qtm/tokens
# with pnpm
pnpm add @qtm/tokens
# with yarn
yarn add @qtm/tokens
/* index.css */
@import '@qtm/tokens/dist/tokens-dark.css';
or into your js entry point
// app.js
import '@qtm/tokens/dist/tokens-dark.css';
The dark mode can be enabled by adding the .dark
class.
<!-- index.html -->
<!-- Dark mode not enabled -->
<html>
...
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
<!-- Dark mode enabled -->
<html class="dark">
...
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
You can also set the dark mode for a specific section or a component.
// app.jsx
import { Button } from '@qtm/react2';
function App() {
return (
<Button variant="filled" color="primary" classes="dark">
Dark button
</Button>
);
}
export default App;
How to bind the dark mode with the system preferences?
On page load dark mode can be set with the user system preferences using the media characteristic (prefers-color-scheme: dark)
.
// On page load dark mode can be set with the user system preferences
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
Using with React Context (Optional)
For a more React-friendly approach, you can create a theme context to manage dark mode:
// ThemeContext.jsx
import React, { createContext, useContext, useState, useEffect } from 'react';
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [darkMode, setDarkMode] = useState(false);
useEffect(() => {
// Initialize based on system preference
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
setDarkMode(true);
}
}, []);
useEffect(() => {
if (darkMode) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [darkMode]);
const toggleDarkMode = () => {
setDarkMode(!darkMode);
};
return (
<ThemeContext.Provider value={{ darkMode, toggleDarkMode }}>
{children}
</ThemeContext.Provider>
);
};
export const useTheme = () => useContext(ThemeContext);
Usage example:
// App.jsx
import { Button } from '@qtm/react2';
import { ThemeProvider, useTheme } from './ThemeContext';
function ThemeToggle() {
const { darkMode, toggleDarkMode } = useTheme();
return (
<Button onClickEvent={toggleDarkMode} classes={darkMode ? 'dark' : ''}>
{darkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'}
</Button>
);
}
function App() {
return (
<ThemeProvider>
<div className="app">
<ThemeToggle />
{/* Your app content */}
</div>
</ThemeProvider>
);
}
export default App;