This is a simple React application that demonstrates how to implement a theme toggler (light/dark mode) using the Context API. The theme is managed globally and can be toggled from any component within the application.
- Context API: Centralized state management for the theme.
- Light/Dark Mode: Toggle between light and dark themes.
- Custom Hook:
useThemehook for easy access to theme context.
First, clone the repository and navigate to the project directory:
git clone https://github.com/CamiloPinzon/Context-API.git
cd Context-APIThen, install the dependencies:
npm installTo start the development server, run:
npm run devThis will start the application on the default Vite port (usually http://localhost:5173).
To build the application for production, run:
npm run buildThe optimized and minified build will be available in the dist directory.
src/context/ThemeContext.tsx: Contains theThemeContext,ThemeProvider, anduseThemehook.src/components/ThemeToggle.tsx: A component that toggles the theme between light and dark.src/App.tsx: The main component that uses the theme context and displays theThemeTogglebutton.src/App.css: Styles for the application, including the light and dark theme classes.
ThemeContext: A context object created using React'screateContext. It holds the current theme and a function to toggle the theme.ThemeProvider: A provider component that wraps the application and provides the theme context to all child components.useTheme: A custom hook that allows easy access to the theme context.
- The
ThemeProviderinsrc/context/ThemeContext.tsxmanages the theme state (lightordark). - The
toggleThemefunction toggles the theme betweenlightanddark. - The
Appcomponent applies the current theme class to the root element, and theThemeTogglecomponent allows users to switch between themes.
import React from 'react';
import ThemeToggle from './components/ThemeToggle';
import { useTheme } from './context/ThemeContext';
import './App.css';
const App: React.FC = () => {
const { theme } = useTheme();
return (
<div className={`app ${theme}`}>
<h1>Hello, Theme Toggler!</h1>
<ThemeToggle />
</div>
);
};
export default App;This project is licensed under the MIT License.