Skip to content

Commit 414dcb9

Browse files
committed
using the global state for theme
1 parent 203a5a1 commit 414dcb9

File tree

3 files changed

+10
-14
lines changed

3 files changed

+10
-14
lines changed

src/components/Navbar.jsx

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,15 @@ import React, { useEffect, useState } from 'react';
22
import logo from '@/assets/images/logo.png';
33
import { Link, useNavigate } from 'react-router-dom';
44
import courses from '@/data/courseData';
5+
import { useTheme } from '@/context/ThemeContext';
6+
57

68
function Navbar({ loggedin }) {
79
const [searchTerm, setSearchTerm] = useState('');
810
const [suggestions, setSuggestions] = useState([]);
9-
const [theme, setTheme] = useState('light');
11+
const { theme, toggleTheme } = useTheme();
1012
const navigate = useNavigate();
1113

12-
const toggleTheme = () => {
13-
const newTheme = theme === 'light' ? 'dark' : 'light';
14-
setTheme(newTheme);
15-
document.body.setAttribute('data-bs-theme', newTheme)
16-
};
17-
1814
const handleSearchChange = (event) => {
1915
const searchInput = event.target.value;
2016
setSearchTerm(searchInput);
@@ -45,11 +41,6 @@ function Navbar({ loggedin }) {
4541
setSuggestions([]);
4642
};
4743

48-
useEffect(() => {
49-
document.body.setAttribute('data-bs-theme', theme);
50-
}, []);
51-
52-
5344
return (
5445
<nav className={`navbar navbar-expand-lg sticky-top bg-body-tertiary navbar-${theme}`}>
5546
<div className="container-fluid">

src/context/ThemeContext.jsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ export const ThemeProvider = ({ children }) => {
66
const [theme, setTheme] = useState('light');
77

88
const toggleTheme = () => {
9-
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
9+
const newTheme = theme === 'light' ? 'dark' : 'light';
10+
setTheme(newTheme);
11+
document.body.setAttribute('data-bs-theme', newTheme);
1012
};
1113

1214
return (

src/main.jsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@ import App from './App.jsx';
44
import './styles/index.css';
55
import 'bootstrap/dist/css/bootstrap.min.css';
66
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
7+
import { ThemeProvider } from './context/ThemeContext.jsx';
78

89
createRoot(document.getElementById('root')).render(
910
<StrictMode>
10-
<App />
11+
<ThemeProvider>
12+
<App />
13+
</ThemeProvider>
1114
</StrictMode>
1215
);

0 commit comments

Comments
 (0)