Skip to content

Commit

Permalink
theme bug resolved
Browse files Browse the repository at this point in the history
  • Loading branch information
pankaj-bind committed May 18, 2024
1 parent 1ae8318 commit fd6e790
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions src/Components/Navbar/Navbar.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext, useState } from 'react';
import React, { useContext, useState, useEffect } from 'react';
import './Navbar.css';
import logo from '../Assets/logo.png';
import cart_icon from '../Assets/cart_icon.png';
Expand All @@ -9,20 +9,34 @@ import { Link } from 'react-router-dom';
import { ShopContext } from '../../Context/ShopContext';

const Navbar = () => {
const { getTotalCartItems, theme, setTheme } = useContext(ShopContext);
const [icon, setIcon] = useState(cart_icon);
const [menu, setMenu] = useState("shop");
const { getTotalCartItems, theme, setTheme } = useContext(ShopContext);

const toggle = () => {
if (theme === "dark") {
setTheme("light");
setIcon(cart_icon_dark);
useEffect(() => {
// Load the theme from localStorage
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
setTheme(savedTheme);
setIcon(savedTheme === "dark" ? cart_icon : cart_icon_dark);
const dnav = document.getElementById("nav");
if (savedTheme === "dark") {
dnav.classList.add("dark");
} else {
dnav.classList.remove("dark");
}
}
}, [setTheme]);

const toggle = () => {
const newTheme = theme === "dark" ? "light" : "dark";
setTheme(newTheme);
localStorage.setItem('theme', newTheme);
setIcon(newTheme === "dark" ? cart_icon : cart_icon_dark);
const dnav = document.getElementById("nav");
if (newTheme === "dark") {
dnav.classList.add("dark");
} else {
setTheme("dark");
setIcon(cart_icon);
const dnav = document.getElementById("nav");
dnav.classList.remove("dark");
}
};
Expand Down Expand Up @@ -55,11 +69,11 @@ const Navbar = () => {
</ul>
<div className="nav-login-cart">
<Link to='/login'><button className='log_btn'>Login</button></Link>
<Link to='/cart'><img src={icon} alt="" className='cart' /></Link>
<Link to='/cart'><img src={icon} alt="Cart Icon" className='cart' /></Link>
<div className="nav-cart-count">{getTotalCartItems()}</div>
<div className='dark_btn'>
<button onClick={toggle} className={`toggle_${theme} change`}>
{theme === 'light' ? <img src={sunIcon} /> : <img src={moonIcon} />}
{theme === 'light' ? <img src={sunIcon} alt="Sun Icon" /> : <img src={moonIcon} alt="Moon Icon" />}
</button>
</div>
</div>
Expand Down

0 comments on commit fd6e790

Please sign in to comment.