Assignments Of Day 13 - useContext Hook
Assignment 1: Create a Theme Toggle Application
Problem Statement:
Create a React application where the user can toggle between "Light Mode" and "Dark Mode" using the useContext hook. The theme should apply globally across all components.
Solution:
1. Create a Theme Context
jsx
Copy code
import React, { createContext, useState } from "react";
export const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
export default ThemeProvider;
2. Wrap the App with ThemeProvider
jsx
Copy code
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import ThemeProvider from "./ThemeContext";
ReactDOM.render(
<ThemeProvider>
<App />
</ThemeProvider>,
document.getElementById("root")
);
3. Consume the Theme in Components
jsx
Copy code
import React, { useContext } from "react";
import { ThemeContext } from "./ThemeContext";
const ThemeSwitcher = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div style={{ backgroundColor: theme === "light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff", padding: "20px" }}>
<h1>{theme === "light" ? "Light Mode" : "Dark Mode"}</h1>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};
export default ThemeSwitcher;
Explanation:
- ThemeContext stores the current theme and a function to toggle it.
- ThemeProvider wraps the application and provides the context.
- The ThemeSwitcher component uses useContext to access the theme and toggle function.
Assignment 2: Create a User Login Context
Problem Statement:
Develop a React app where a user can log in by entering a name. Display the logged-in user's name globally across the app without prop drilling.
Solution:
1. Create a User Context
jsx
Copy code
import React, { createContext, useState } from "react";
export const UserContext = createContext();
const UserProvider = ({ children }) => {
const [user, setUser] = useState("");
const loginUser = (name) => {
setUser(name);
};
return (
<UserContext.Provider value={{ user, loginUser }}>
{children}
</UserContext.Provider>
);
};
export default UserProvider;
2. Wrap the App with UserProvider
jsx
Copy code
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import UserProvider from "./UserContext";
ReactDOM.render(
<UserProvider>
<App />
</UserProvider>,
document.getElementById("root")
);
3. Create a Login Component
jsx
Copy code
import React, { useContext, useState } from "react";
import { UserContext } from "./UserContext";
const Login = () => {
const [name, setName] = useState("");
const { loginUser } = useContext(UserContext);
const handleLogin = () => {
loginUser(name);
};
return (
<div>
<input type="text" placeholder="Enter Name" value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default Login;
4. Display Logged-In User
jsx
Copy code
import React, { useContext } from "react";
import { UserContext } from "./UserContext";
const UserProfile = () => {
const { user } = useContext(UserContext);
return <h1>{user ? `Welcome, ${user}!` : "Please Log In"}</h1>;
};
export default UserProfile;
5. Combine Components in App
jsx
Copy code
import React from "react";
import Login from "./Login";
import UserProfile from "./UserProfile";
const App = () => {
return (
<div>
<UserProfile />
<Login />
</div>
);
};
export default App;
Explanation:
- UserContext stores the logged-in user's name and a function to update it.
- The Login component updates the user's name in the context.
- The UserProfile component accesses the user from the context and displays it.
Assignment 3: Create a Multi-Language Application
Problem Statement:
Build an application where users can switch between English and Spanish using a dropdown. The selected language should apply globally.
Solution:
1. Create a Language Context
jsx
Copy code
import React, { createContext, useState } from "react";
export const LanguageContext = createContext();
const LanguageProvider = ({ children }) => {
const [language, setLanguage] = useState("en");
const changeLanguage = (lang) => {
setLanguage(lang);
};
return (
<LanguageContext.Provider value={{ language, changeLanguage }}>
{children}
</LanguageContext.Provider>
);
};
export default LanguageProvider;
2. Implement Language Selector Component
jsx
Copy code
import React, { useContext } from "react";
import { LanguageContext } from "./LanguageContext";
const LanguageSelector = () => {
const { language, changeLanguage } = useContext(LanguageContext);
return (
<div>
<select value={language} onChange={(e) => changeLanguage(e.target.value)}>
<option value="en">English</option>
<option value="es">Spanish</option>
</select>
</div>
);
};
export default LanguageSelector;
3. Display Language-Specific Content
jsx
Copy code
import React, { useContext } from "react";
import { LanguageContext } from "./LanguageContext";
const Greeting = () => {
const { language } = useContext(LanguageContext);
return <h1>{language === "en" ? "Hello, World!" : "¡Hola, Mundo!"}</h1>;
};
export default Greeting;
4. Combine Components in App
jsx
Copy code
import React from "react";
import Greeting from "./Greeting";
import LanguageSelector from "./LanguageSelector";
const App = () => {
return (
<div>
<LanguageSelector />
<Greeting />
</div>
);
};
export default App;
Explanation:
- The LanguageContext manages the selected language.
- LanguageSelector allows users to switch languages.
- Greeting displays content based on the selected language.
By completing these assignments, students will gain hands-on experience in:
1. Using useContext to manage global state.
2. Avoiding prop drilling.
3. Building flexible and scalable React applications.
4o
You said:
some more
ChatGPT said:
ChatGPT
More Assignments on useContext Hook
Assignment 4: Create a Cart Management System
Problem Statement:
Develop a simple e-commerce cart system where users can add items to the cart. Display the cart's total items and allow users to view the list of added items using useContext.
Solution:
1. Create a Cart Context
jsx
Copy code
import React, { createContext, useState } from "react";
export const CartContext = createContext();
const CartProvider = ({ children }) => {
const [cart, setCart] = useState([]);
const addToCart = (item) => {
setCart((prevCart) => [...prevCart, item]);
};
return (
<CartContext.Provider value={{ cart, addToCart }}>
{children}
</CartContext.Provider>
);
};
export default CartProvider;
2. Wrap the App with CartProvider
jsx
Copy code
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import CartProvider from "./CartContext";
ReactDOM.render(
<CartProvider>
<App />
</CartProvider>,
document.getElementById("root")
);
3. Create a Product List Component
jsx
Copy code
import React, { useContext } from "react";
import { CartContext } from "./CartContext";
const ProductList = () => {
const { addToCart } = useContext(CartContext);
const products = ["Apple", "Banana", "Orange"];
return (
<div>
<h2>Products</h2>
{products.map((product, index) => (
<div key={index}>
<span>{product}</span>
<button onClick={() => addToCart(product)}>Add to Cart</button>
</div>
))}
</div>
);
};
export default ProductList;
4. Create a Cart Display Component
jsx
Copy code
import React, { useContext } from "react";
import { CartContext } from "./CartContext";
const Cart = () => {
const { cart } = useContext(CartContext);
return (
<div>
<h2>Cart</h2>
<p>Total Items: {cart.length}</p>
<ul>
{cart.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
};
export default Cart;
5. Combine Components in App
jsx
Copy code
import React from "react";
import ProductList from "./ProductList";
import Cart from "./Cart";
const App = () => {
return (
<div>
<ProductList />
<Cart />
</div>
);
};
export default App;
Explanation:
- The CartContext manages the cart state.
- The ProductList component adds items to the cart using the addToCart function from the context.
- The Cart component displays the total items and the list of products in the cart.
Assignment 5: Create a Multi-Page Navigation System
Problem Statement:
Build a React app with three pages: Home, About, and Contact. Use useContext to manage the current page's state globally and navigate between the pages.
Solution:
1. Create a Navigation Context
jsx
Copy code
import React, { createContext, useState } from "react";
export const NavContext = createContext();
const NavProvider = ({ children }) => {
const [currentPage, setCurrentPage] = useState("Home");
return (
<NavContext.Provider value={{ currentPage, setCurrentPage }}>
{children}
</NavContext.Provider>
);
};
export default NavProvider;
2. Wrap the App with NavProvider
jsx
Copy code
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import NavProvider from "./NavContext";
ReactDOM.render(
<NavProvider>
<App />
</NavProvider>,
document.getElementById("root")
);
3. Create a Navigation Component
jsx
Copy code
import React, { useContext } from "react";
import { NavContext } from "./NavContext";
const Navigation = () => {
const { setCurrentPage } = useContext(NavContext);
return (
<nav>
<button onClick={() => setCurrentPage("Home")}>Home</button>
<button onClick={() => setCurrentPage("About")}>About</button>
<button onClick={() => setCurrentPage("Contact")}>Contact</button>
</nav>
);
};
export default Navigation;
4. Display Content Based on Current Page
jsx
Copy code
import React, { useContext } from "react";
import { NavContext } from "./NavContext";
const Content = () => {
const { currentPage } = useContext(NavContext);
return (
<div>
{currentPage === "Home" && <h1>Welcome to the Home Page</h1>}
{currentPage === "About" && <h1>About Us</h1>}
{currentPage === "Contact" && <h1>Contact Us</h1>}
</div>
);
};
export default Content;
5. Combine Components in App
jsx
Copy code
import React from "react";
import Navigation from "./Navigation";
import Content from "./Content";
const App = () => {
return (
<div>
<Navigation />
<Content />
</div>
);
};
export default App;
Explanation:
- The NavContext keeps track of the current page.
- The Navigation component updates the page using setCurrentPage.
- The Content component displays the corresponding content based on the current page.
Assignment 6: Create a Notification System
Problem Statement:
Create a React app where notifications can be added dynamically and displayed globally across the app using useContext.
Solution:
1. Create a Notification Context
jsx
Copy code
import React, { createContext, useState } from "react";
export const NotificationContext = createContext();
const NotificationProvider = ({ children }) => {
const [notifications, setNotifications] = useState([]);
const addNotification = (message) => {
setNotifications((prev) => [...prev, message]);
};
return (
<NotificationContext.Provider value={{ notifications, addNotification }}>
{children}
</NotificationContext.Provider>
);
};
export default NotificationProvider;
2. Display Notifications
jsx
Copy code
import React, { useContext } from "react";
import { NotificationContext } from "./NotificationContext";
const NotificationList = () => {
const { notifications } = useContext(NotificationContext);
return (
<div>
<h2>Notifications</h2>
<ul>
{notifications.map((notification, index) => (
<li key={index}>{notification}</li>
))}
</ul>
</div>
);
};
export default NotificationList;
3. Add Notifications
jsx
Copy code
import React, { useContext } from "react";
import { NotificationContext } from "./NotificationContext";
const AddNotification = () => {
const { addNotification } = useContext(NotificationContext);
return (
<button onClick={() => addNotification("New Notification!")}>
Add Notification
</button>
);
};
export default AddNotification;
4. Combine Components in App
jsx
Copy code
import React from "react";
import NotificationList from "./NotificationList";
import AddNotification from "./AddNotification";
const App = () => {
return (
<div>
<AddNotification />
<NotificationList />
</div>
);
};
export default App;
Explanation:
- The NotificationContext manages the list of notifications.
- Notifications can be dynamically added and displayed across the app.
