Description:
I’ve implemented a theme switching button in my React application to toggle between light and dark themes. However, I’m encountering an issue where clicking the button doesn’t result in the theme changing as expected.
Here’s the relevant code snippet from my application:
import React, { useState } from 'react';
import RecruitmentList from './components/RecruitmentList';
import './App.css';
function App() {
const [darkMode, setDarkMode] = useState(false);
const toggleDarkMode = () => {
setDarkMode(!darkMode);
};
return (
<div className={`App ${darkMode ? 'dark-mode' : 'light-mode'}`}>
<header className="App-header">
<div className="mode-switcher" onClick={toggleDarkMode}>
<div className={`toggle ${darkMode ? 'toggle-dark' : 'toggle-light'}`} />
</div>
<RecruitmentList />
</header>
</div>
);
}
export default App;
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.mode-switcher {
position: absolute;
top: 20px;
right: 20px;
cursor: pointer;
}
.toggle {
width: 60px;
height: 30px;
background-color: #ccc;
border-radius: 15px;
transition: all 0.3s ease;
}
.toggle-light {
background-color: #ddd;
}
.toggle-dark {
background-color: #333;
}
.toggle::after {
content: '';
position: absolute;
width: 26px;
height: 26px;
background-color: #fff;
border-radius: 50%;
top: 50%;
transform: translateY(-50%);
transition: all 0.3s ease;
}
.toggle-light::after {
left: 4px;
}
.toggle-dark::after {
left: calc(100% - 30px);
}
Despite clicking the "Toggle Theme" button, the theme remains unchanged. I’ve checked the event handling and state updating logic, but I can’t seem to identify the issue.
Could someone please help me understand why the theme isn’t changing when the button is clicked? Any insights or suggestions would be greatly appreciated. Thank you!
2
Answers
Your code seems just fine.
But how about you try this?
And if this doesn’t work, you could close your React app and then restarts it. But be sure to check if there are errors on your console first.
It had multiple issues.
.App
classI have corrected the CSS. Replace your CSS with below code –
This toggle seems to be working fine with above changes.