buttonToggle component is a React-based interactive button that allows users to switch between light and dark themes. It uses React Icons for visual indicators and manages theme state internally.
Props
This component accepts no props. It manages its own internal state.Features
Theme State Management
The component uses ReactuseState hook to track the current theme:
"light" on initial render.
Theme Toggle Logic
On button click, the component:- Toggles internal state between
"light"and"dark" - Calls the
toggleTheme()utility to update the DOM
Visual Indicators
The button displays different icons based on current theme:- Light mode: Shows moon icon (
FaMoon) to indicate “switch to dark” - Dark mode: Shows sun icon (
FaSun) to indicate “switch to light”
How Dark Mode Works
ThetoggleTheme utility function toggles the dark class on the document root:
.dark class selector:
Styling
The component includes inline styles:- Center the icon within the button
- Provide comfortable click target size
- Add spacing between icon and any potential text
Usage Example
Accessibility Considerations
To improve accessibility, consider adding:Dependencies
- React: For state management and component lifecycle
- react-icons: Provides
FaSunandFaMoonicons from Font Awesome - toggleTheme: Utility function that manipulates DOM classes
Persistence
Note: The current implementation does not persist theme preference. Theme resets to"light" on page refresh.
To add persistence, consider using localStorage:
Source
Location:src/components/buttonToggle.jsx:7
Toggle utility: src/components/toggleTheme.jsx:4