I’m encountering an issue with implementing dark mode styles in my web application. I’ve followed the recommended approach of using Tailwind CSS’s built-in dark mode support by adding the ‘dark’ class to the HTML tree, but for some reason, the dark mode styles are not being applied.
Specifically, I’m trying to get ‘dark:bg-bgDark’ to be applied when darkMode is toggled. Currently, the background stays constant to bg-bgLight.
My tailwind.config.js:
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
theme: {
darkMode: 'selector',
extend: {
boxShadow: {
'custom': '0 2px 4px rgba(0, 0, 0, 0.1)'
},
},
screens: {
'sm': {'max': '550px'},
},
colors: {
bgLight: 'hsl(0, 0%, 98%)',
textColor: 'hsl(200, 15%, 8%)',
bgDark: 'hsl(207, 26%, 17%)'
},
fontSize: {
'sm': ['0.875rem', { lineHeight: '1.25rem' }],
'md': ['1.2rem', { lineHeight: '1.75rem' }],
'big': '28px'
},
},
plugins: [],
};
My HomePage.jsx:
import { Header, CountryCard } from "../components";
import { SearchBar, Filter } from '../utils'
import countries from "../assets/data.json";
import useTheme from '../hooks/useTheme'
const HomePage = () => {
const [toggleTheme, theme] = useTheme()
return (
<div className="bg-bgLight dark:bg-bgDark">
<Header theme={theme} toggleTheme={toggleTheme} />
<div className="flex m-10 justify-between">
<SearchBar />
<Filter countries={countries} />
</div>
<div className="flex flex-wrap justify-center">
{countries.map((country) => (
<CountryCard key={country.alpha3Code} country={country} />
))}
</div>
</div>
);
};
export default HomePage;
useTheme.jsx:
import { Header, CountryCard } from "../components";
import { SearchBar, Filter } from '../utils'
import countries from "../assets/data.json";
import useTheme from '../hooks/useTheme'
const HomePage = () => {
const [toggleTheme, theme] = useTheme()
return (
<div className="bg-bgLight dark:bg-bgDark">
<Header theme={theme} toggleTheme={toggleTheme} />
<div className="flex m-10 justify-between">
<SearchBar />
<Filter countries={countries} />
</div>
<div className="flex flex-wrap justify-center">
{countries.map((country) => (
<CountryCard key={country.alpha3Code} country={country} />
))}
</div>
</div>
);
};
export default HomePage;
I tried using ‘class’ instead of ‘selector’ in the config for darkMode.
I made sure the class ‘dark’ was being applied and removed accordingly to the HTML element on the DOM when toggling darkMode.
I made sure local storage and state was updating properly.