@asafarim/themeswitch
v28.6.2024
Published
A React package for theme switching between light and dark modes, utilizing a context provider and a switcher component.
Downloads
7
Readme
Package @asafarim/themeswitch
A React package for theme switching between light and dark modes, utilizing a context provider and a switcher component.
Installation
To install the package, run the following command:
npm install @asafarim/themeswitch
or with Yarn:
yarn add @asafarim/themeswitch
Usage
ThemeProvider
Wrap your application with the ThemeProvider
to provide theme context to your components.
import React from 'react';
import ReactDOM from 'react-dom';
import { ThemeProvider } from '@asafarim/themeswitch';
import App from './App';
ReactDOM.render(
<ThemeProvider>
<App />
</ThemeProvider>,
document.getElementById('root')
);
useTheme Hook
Use the useTheme
hook to access the current theme and the toggleTheme
function.
import React from 'react';
import { useTheme } from '@asafarim/themeswitch';
const ThemedComponent: React.FC = () => {
const { theme, toggleTheme } = useTheme();
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};
export default ThemedComponent;
ThemeSwitcher Component
Use the ThemeSwitcher
component to provide a ready-made theme switcher.
import React from 'react';
import { ThemeSwitcher } from '@asafarim/themeswitch';
const App: React.FC = () => {
return (
<div>
<h1>My Themed App</h1>
<ThemeSwitcher />
</div>
);
};
export default App;
CSS Styles
Include the following CSS styles for the ThemeSwitcher
component:
/* ThemeSwitcher.css */
.themeSwitcherToggle {
cursor: pointer;
font-size: 1.5rem;
font-weight: 600;
color: #fff;
background-color: #555;
border: none;
border-radius: 5px;
padding: 0.5rem 1rem;
transition: all 0.2s ease-in-out;
outline: none;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5);
width: 100px;
}
.toggle-icon {
width: 10px;
height: 10px;
background-color: #fff;
border-radius: 50%;
border: 1px solid #fff;
display: flex;
justify-content: center;
}
.ThemeSwitcherToggleIcon {
width: 10px;
height: 10px;
background-color: #fff;
border-radius: 50%;
border: 1px solid #fff;
display: flex;
justify-content: center;
}
.toggle-tooltip {
position: absolute;
top: 100%;
left: 50%;
transform: translate(-50%, 0);
background-color: #555;
color: #f01212;
padding: 0.5rem 1rem;
border-radius: 5px;
font-size: 1.2rem;
font-weight: 600;
}
.rightAligned {
margin-left: auto;
display: flex;
align-items: center;
}
Example
Here is a complete example of how to use the package in your project:
import React from 'react';
import ReactDOM from 'react-dom';
import { ThemeProvider, ThemeSwitcher } from '@asafarim/themeswitch';
import './ThemeSwitcher.css';
const App: React.FC = () => {
return (
<ThemeProvider>
<div>
<h1>My Themed App</h1>
<ThemeSwitcher />
</div>
</ThemeProvider>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
License
This project is licensed under the MIT License.
Author
Ali Safari