KEMBAR78
1 Khanki | PDF | Function (Mathematics) | Password
0% found this document useful (0 votes)
35 views36 pages

1 Khanki

The document outlines the structure and functionality of various React components used in a frontend application, including BestSeller, CartTotal, Footer, Hero, LatestCollection, Navbar, NewsletterBox, OurPolicy, ProductItem, RelatedProducts, and SearchBar. Each component includes details about imports, state management using hooks, JSX structure, and export statements. The components are designed to handle product listings, cart totals, navigation, and user interactions effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views36 pages

1 Khanki

The document outlines the structure and functionality of various React components used in a frontend application, including BestSeller, CartTotal, Footer, Hero, LatestCollection, Navbar, NewsletterBox, OurPolicy, ProductItem, RelatedProducts, and SearchBar. Each component includes details about imports, state management using hooks, JSX structure, and export statements. The components are designed to handle product listings, cart totals, navigation, and user interactions effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

FrontEnd:-

Components:-

BestSeller.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect, useState from 'react'
- ShopContext from '../context/ShopContext'
- Title from './Title'
- ProductItem from './ProductItem'

2. Define the BestSeller component:


- Use the useContext hook to get the products from ShopContext
- Initialize a state variable bestSeller with an empty array using useState

3. Use the useEffect hook to filter and set the best-selling products:
- Filter the products array to get items marked as bestseller
- Set the bestSeller state with the top 5 best-selling products

4. Return the JSX structure:


- A div with class 'my-10'
- A nested div with class 'text-center text-3xl py-8'
- Render the Title component with text1 as 'BEST' and text2 as 'SELLERS'
- Render a paragraph with class 'w-3/4 m-auto text-xs sm:text-sm md:text-base text-gray-600'
containing a description of the best-selling products
- A nested div with class 'grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4 gap-y-6'
- Map over the bestSeller array and render a ProductItem component for each item with key, id,
name, image, and price props

5. Export the BestSeller component as the default export

CartTotal.jsx:-

1. Import necessary modules and components:


- React, useContext from 'react'
- ShopContext from '../context/ShopContext'
- Title from './Title'

2. Define the CartTotal component:


- Use the useContext hook to get currency, delivery_fee, and getCartAmount from ShopContext

3. Return the JSX structure:


- A div with class 'w-full'
- A nested div with class 'text-2xl'
- Render the Title component with text1 as 'CART' and text2 as 'TOTALS'
- A nested div with class 'flex flex-col gap-2 mt-2 text-sm'
- A nested div with class 'flex justify-between'
- Render a paragraph with text 'Subtotal'
- Render a paragraph with currency and the result of getCartAmount() followed by '.00'
- Render a horizontal rule (hr)
- A nested div with class 'flex justify-between'
- Render a paragraph with text 'Shipping Fee'
- Render a paragraph with currency and delivery_fee followed by '.00'
- Render a horizontal rule (hr)
- A nested div with class 'flex justify-between'
- Render a bold paragraph with text 'Total'
- Render a bold paragraph with currency and the result of getCartAmount() + delivery_fee (or 0
if getCartAmount() is 0) followed by '.00'

4. Export the CartTotal component as the default export

Footer.jsx:-

1. Import necessary modules and components:


- React from 'react'
- assets from '../assets/assets'

2. Define the Footer component:

3. Return the JSX structure:


- A div
- A nested div with class 'flex flex-col sm:grid grid-cols-[3fr_1fr_1fr] gap-14 my-10 mt-40 text-sm'
- A nested div
- Render an image with src as assets.logo, class 'mb-5 w-32', and an empty alt attribute
- Render a paragraph with class 'w-full md:w-2/3 text-gray-600' containing a description of the
company
- A nested div
- Render a paragraph with class 'text-xl font-medium mb-5' with text 'COMPANY'
- Render an unordered list with class 'flex flex-col gap-1 text-gray-600'
- Render list items with text 'Home', 'About us', 'Delivery', and 'Privacy policy'
- A nested div
- Render a paragraph with class 'text-xl font-medium mb-5' with text 'GET IN TOUCH'
- Render an unordered list with class 'flex flex-col gap-1 text-gray-600'
- Render list items with text '+91-74391 38463' and 'sohanc340@gmail.com'
- A nested div
- Render a horizontal rule (hr)
- Render a paragraph with class 'py-5 text-sm text-center' with text 'Copyright 2024@
forever.com - All Right Reserved.'

4. Export the Footer component as the default export

Hero.jsx:-

1. Import necessary modules and components:


- React from 'react'
- assets from '../assets/assets'

2. Define the Hero component:

3. Return the JSX structure:


- A div with class 'flex flex-col sm:flex-row border border-gray-400'
- A nested div with class 'w-full sm:w-1/2 flex items-center justify-center py-10 sm:py-0'
- A nested div with class 'text-[#414141]'
- A nested div with class 'flex items-center gap-2'
- Render a paragraph with class 'w-8 md:w-11 h-[2px] bg-[#414141]'
- Render a paragraph with class 'font-medium text-sm md:text-base' with text 'OUR
BESTSELLERS'
- Render a heading with class 'prata-regular text-3xl sm:py-3 lg:text-5xl leading-relaxed' with text
'Latest Arrivals'
- A nested div with class 'flex items-center gap-2'
- Render a paragraph with class 'font-semibold text-sm md:text-base' with text 'SHOP NOW'
- Render a paragraph with class 'w-8 md:w-11 h-[1px] bg-[#414141]'
- Render an image with class 'w-full sm:w-1/2', src as assets.hero_img, and an empty alt attribute

4. Export the Hero component as the default export

LatestCollection.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect, useState from 'react'
- ShopContext from '../context/ShopContext'
- Title from './Title'
- ProductItem from './ProductItem'

2. Define the LatestCollection component:


- Use the useContext hook to get the products from ShopContext
- Initialize a state variable latestProducts with an empty array using useState

3. Use the useEffect hook to set the latest products:


- Set the latestProducts state with the first 10 products from the products array

4. Return the JSX structure:


- A div with class 'my-10'
- A nested div with class 'text-center py-8 text-3xl'
- Render the Title component with text1 as 'LATEST' and text2 as 'COLLECTIONS'
- Render a paragraph with class 'w-3/4 m-auto text-xs sm:text-sm md:text-base text-gray-600'
containing a description of the latest collections
- A nested div with class 'grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4 gap-y-6'
- Map over the latestProducts array and render a ProductItem component for each item with key,
id, image, name, and price props

5. Export the LatestCollection component as the default export

Navbar.jsx:-

1. Import necessary modules and components:


- React, useContext, useState from 'react'
- assets from '../assets/assets'
- Link, NavLink from 'react-router-dom'
- ShopContext from '../context/ShopContext'

2. Define the Navbar component:


- Initialize a state variable visible with false using useState
- Use the useContext hook to get setShowSearch, getCartCount, navigate, token, setToken, and
setCartItems from ShopContext

3. Define the logout function:


- Navigate to '/login'
- Remove 'token' from localStorage
- Set token to an empty string
- Set cartItems to an empty object

4. Return the JSX structure:


- A div with class 'flex items-center justify-between py-5 font-medium'
- A Link to '/' containing an image with src as assets.logo, class 'w-36', and an empty alt attribute
- An unordered list with class 'hidden sm:flex gap-5 text-sm text-gray-700'
- NavLink to '/' with class 'flex flex-col items-center gap-1' containing a paragraph with text
'HOME' and a hidden horizontal rule
- NavLink to '/collection' with class 'flex flex-col items-center gap-1' containing a paragraph with
text 'COLLECTION' and a hidden horizontal rule
- NavLink to '/about' with class 'flex flex-col items-center gap-1' containing a paragraph with text
'ABOUT' and a hidden horizontal rule
- NavLink to '/contact' with class 'flex flex-col items-center gap-1' containing a paragraph with
text 'CONTACT' and a hidden horizontal rule
- A div with class 'flex items-center gap-6'
- An image with src as assets.search_icon, class 'w-5 cursor-pointer', and an empty alt attribute,
with an onClick event to setShowSearch(true) and navigate('/collection')
- A div with class 'group relative'
- An image with src as assets.profile_icon, class 'w-5 cursor-pointer', and an empty alt attribute,
with an onClick event to navigate('/login') if token is not present
- If token is present, render a dropdown menu with class 'group-hover:block hidden absolute
dropdown-menu right-0 pt-4'
- A div with class 'flex flex-col gap-2 w-36 py-3 px-5 bg-slate-100 text-gray-500 rounded'
- A paragraph with text 'My Profile' and class 'cursor-pointer hover:text-black'
- A paragraph with text 'Orders', class 'cursor-pointer hover:text-black', and an onClick event
to navigate('/orders')
- A paragraph with text 'Logout', class 'cursor-pointer hover:text-black', and an onClick event
to logout
- A Link to '/cart' with class 'relative' containing an image with src as assets.cart_icon, class 'w-5
min-w-5', and an empty alt attribute, and a paragraph with class 'absolute right-[-5px] bottom-[-5px]
w-4 text-center leading-4 bg-black text-white aspect-square rounded-full text-[8px]' containing the
result of getCartCount()
- An image with src as assets.menu_icon, class 'w-5 cursor-pointer sm:hidden', and an empty alt
attribute, with an onClick event to setVisible(true)
- A div with class 'absolute top-0 right-0 bottom-0 overflow-hidden bg-white transition-all' and a
dynamic class based on the value of visible
- A div with class 'flex flex-col text-gray-600'
- A div with class 'flex items-center gap-4 p-3 cursor-pointer' and an onClick event to
setVisible(false)
- An image with class 'h-4 rotate-180' and src as assets.dropdown_icon, and an empty alt
attribute
- A paragraph with text 'Back'
- NavLink to '/' with class 'py-2 pl-6 border' and an onClick event to setVisible(false) containing
text 'HOME'
- NavLink to '/collection' with class 'py-2 pl-6 border' and an onClick event to setVisible(false)
containing text 'COLLECTION'
- NavLink to '/about' with class 'py-2 pl-6 border' and an onClick event to setVisible(false)
containing text 'ABOUT'
- NavLink to '/contact' with class 'py-2 pl-6 border' and an onClick event to setVisible(false)
containing text 'CONTACT'

5. Export the Navbar component as the default export

NewsLetterBox.jsx:-

1. Import necessary modules and components:


- React from 'react'

2. Define the NewsletterBox component:

3. Define the onSubmitHandler function:


- Prevent the default form submission behavior

4. Return the JSX structure:


- A div with class 'text-center'
- A paragraph with class 'text-2xl font-medium text-gray-800' with text 'Subscribe now & get 20%
off'
- A paragraph with class 'text-gray-400 mt-3' containing a description of the newsletter benefits
- A form with onSubmit event set to onSubmitHandler and class 'w-full sm:w-1/2 flex items-center
gap-3 mx-auto my-6 border pl-3'
- An input with class 'w-full sm:flex-1 outline-none', type 'email', placeholder 'Enter your email',
and required attribute
- A button with type 'submit', class 'bg-black text-white text-xs px-10 py-4', and text 'SUBSCRIBE'

5. Export the NewsletterBox component as the default export

OurPolicy.jsx:-

1. Import necessary modules and components:


- React from 'react'
- assets from '../assets/assets'

2. Define the OurPolicy component:

3. Return the JSX structure:


- A div with class 'flex flex-col sm:flex-row justify-around gap-12 sm:gap-2 text-center py-20 text-xs
sm:text-sm md:text-base text-gray-700'
- A nested div
- Render an image with src as assets.exchange_icon, class 'w-12 m-auto mb-5', and an empty alt
attribute
- Render a paragraph with class 'font-semibold' with text 'Easy Exchange Policy'
- Render a paragraph with class 'text-gray-400' with text 'We offer hassle free exchange policy'
- A nested div
- Render an image with src as assets.quality_icon, class 'w-12 m-auto mb-5', and an empty alt
attribute
- Render a paragraph with class 'font-semibold' with text '7 Days Return Policy'
- Render a paragraph with class 'text-gray-400' with text 'We provide 7 days free return policy'
- A nested div
- Render an image with src as assets.support_img, class 'w-12 m-auto mb-5', and an empty alt
attribute
- Render a paragraph with class 'font-semibold' with text 'Best customer support'
- Render a paragraph with class 'text-gray-400' with text 'we provide 24/7 customer support'

4. Export the OurPolicy component as the default export

ProductItem.jsx:-

1. Import necessary modules and components:


- React, useContext from 'react'
- ShopContext from '../context/ShopContext'
- Link from 'react-router-dom'

2. Define the ProductItem component:


- Destructure id, image, name, and price from the component's props
- Use the useContext hook to get currency from ShopContext

3. Return the JSX structure:


- A Link component with an onClick event to scroll to the top of the page, class 'text-gray-700
cursor-pointer', and to attribute set to `/product/${id}`
- A nested div with class 'overflow-hidden'
- Render an image with src as the first element of the image array, class 'hover:scale-110
transition ease-in-out', and an empty alt attribute
- Render a paragraph with class 'pt-3 pb-1 text-sm' containing the product name
- Render a paragraph with class 'text-sm font-medium' containing the currency and price

4. Export the ProductItem component as the default export

RelatedProducts.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect, useState from 'react'
- ShopContext from '../context/ShopContext'
- Title from './Title'
- ProductItem from './ProductItem'

2. Define the RelatedProducts component:


- Destructure category and subCategory from the component's props
- Use the useContext hook to get the products from ShopContext
- Initialize a state variable related with an empty array using useState

3. Use the useEffect hook to set the related products:


- Check if the products array has more than 0 items
- Create a copy of the products array
- Filter the productsCopy array to get items that match the category
- Filter the productsCopy array to get items that match the subCategory
- Set the related state with the first 5 items from the filtered productsCopy array
4. Return the JSX structure:
- A div with class 'my-24'
- A nested div with class 'text-center text-3xl py-2'
- Render the Title component with text1 as 'RELATED' and text2 as 'PRODUCTS'
- A nested div with class 'grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4 gap-y-6'
- Map over the related array and render a ProductItem component for each item with key, id,
name, price, and image props

5. Export the RelatedProducts component as the default export

SearchBar.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect, useState from 'react'
- ShopContext from '../context/ShopContext'
- assets from '../assets/assets'
- useLocation from 'react-router-dom'

2. Define the SearchBar component:


- Use the useContext hook to get search, setSearch, showSearch, and setShowSearch from
ShopContext
- Initialize a state variable visible with false using useState
- Use the useLocation hook to get the current location

3. Use the useEffect hook to set the visibility of the search bar:
- Check if the current location pathname includes 'collection'
- If true, set visible to true
- If false, set visible to false

4. Return the JSX structure:


- If showSearch and visible are true, render the following:
- A div with class 'border-t border-b bg-gray-50 text-center'
- A nested div with class 'inline-flex items-center justify-center border border-gray-400 px-5 py-2
my-5 mx-3 rounded-full w-3/4 sm:w-1/2'
- Render an input with value set to search, onChange event to update search, class 'flex-1
outline-none bg-inherit text-sm', type 'text', and placeholder 'Search'
- Render an image with class 'w-4', src as assets.search_icon, and an empty alt attribute
- Render an image with class 'inline w-3 cursor-pointer', src as assets.cross_icon, and an empty
alt attribute, with an onClick event to setShowSearch(false)
- If showSearch or visible are false, render null

5. Export the SearchBar component as the default export

Title.jsx:-

1. Import necessary modules and components:


- React from 'react'

2. Define the Title component:


- Destructure text1 and text2 from the component's props
3. Return the JSX structure:
- A div with class 'inline-flex gap-2 items-center mb-3'
- Render a paragraph with class 'text-gray-500' containing text1 and a nested span with class 'text-
gray-700 font-medium' containing text2
- Render a paragraph with class 'w-8 sm:w-12 h-[1px] sm:h-[2px] bg-gray-700'

4. Export the Title component as the default export

Context:-
ShopContext.jsx:-

1. Import necessary modules and components:


- createContext, useEffect, useState from 'react'
- toast from 'react-toastify'
- useNavigate from 'react-router-dom'
- axios from 'axios'

2. Create the ShopContext using createContext

3. Define the ShopContextProvider component:


- Initialize constants: currency, delivery_fee, backendUrl
- Initialize state variables: search, showSearch, cartItems, products, token
- Use the useNavigate hook to get the navigate function

4. Define the addToCart function:


- Check if size is provided, if not, show an error toast
- Create a copy of cartItems
- Update the cartData with the new item and size
- Set the cartItems state with the updated cartData
- If token is present, send a POST request to add the item to the cart in the backend

5. Define the getCartCount function:


- Initialize totalCount to 0
- Loop through cartItems and count the total number of items
- Return totalCount

6. Define the updateQuantity function:


- Create a copy of cartItems
- Update the quantity of the specified item and size
- Set the cartItems state with the updated cartData
- If token is present, send a POST request to update the item quantity in the backend

7. Define the getCartAmount function:


- Initialize totalAmount to 0
- Loop through cartItems and calculate the total amount based on item prices and quantities
- Return totalAmount

8. Define the getProductsData function:


- Send a GET request to fetch the product list from the backend
- If successful, set the products state with the fetched products
- If an error occurs, show an error toast

9. Define the getUserCart function:


- Send a POST request to fetch the user's cart data from the backend
- If successful, set the cartItems state with the fetched cart data
- If an error occurs, show an error toast

10. Use the useEffect hook to fetch products data on component mount

11. Use the useEffect hook to fetch user cart data if token is present or stored in localStorage

12. Define the value object containing the context values

13. Return the ShopContext.Provider component with the value object and props.children

14. Export the ShopContextProvider component as the default export

Pages:-
About.jsx:-

1. Import necessary modules and components:


- React from 'react'
- Title from '../components/Title'
- assets from '../assets/assets'
- NewsletterBox from '../components/NewsletterBox'

2. Define the About component:

3. Return the JSX structure:


- A div
- A nested div with class 'text-2xl text-center pt-8 border-t'
- Render the Title component with text1 as 'ABOUT' and text2 as 'US'
- A nested div with class 'my-10 flex flex-col md:flex-row gap-16'
- Render an image with class 'w-full md:max-w-[450px]', src as assets.about_img, and an empty
alt attribute
- A nested div with class 'flex flex-col justify-center gap-6 md:w-2/4 text-gray-600'
- Render a paragraph with text about the company's origin and mission
- Render a paragraph with text about the company's product selection
- Render a bold paragraph with class 'text-gray-800' with text 'Our Mission'
- Render a paragraph with text about the company's mission
- A nested div with class 'text-xl py-4'
- Render the Title component with text1 as 'WHY' and text2 as 'CHOOSE US'
- A nested div with class 'flex flex-col md:flex-row text-sm mb-20'
- A nested div with class 'border px-10 md:px-16 py-8 sm:py-20 flex flex-col gap-5'
- Render a bold paragraph with text 'Quality Assurance:'
- Render a paragraph with class 'text-gray-600' with text about quality assurance
- A nested div with class 'border px-10 md:px-16 py-8 sm:py-20 flex flex-col gap-5'
- Render a bold paragraph with text 'Convenience:'
- Render a paragraph with class 'text-gray-600' with text about convenience
- A nested div with class 'border px-10 md:px-16 py-8 sm:py-20 flex flex-col gap-5'
- Render a bold paragraph with text 'Exceptional Customer Service:'
- Render a paragraph with class 'text-gray-600' with text about customer service
- Render the NewsletterBox component

4. Export the About component as the default export

Cart.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect, useState from 'react'
- ShopContext from '../context/ShopContext'
- Title from '../components/Title'
- assets from '../assets/assets'
- CartTotal from '../components/CartTotal'

2. Define the Cart component:


- Use the useContext hook to get products, currency, cartItems, updateQuantity, and navigate from
ShopContext
- Initialize a state variable cartData with an empty array using useState

3. Use the useEffect hook to set the cart data:


- Check if the products array has more than 0 items
- Create a temporary array tempData
- Loop through cartItems and add items with quantity greater than 0 to tempData
- Set the cartData state with tempData

4. Return the JSX structure:


- A div with class 'border-t pt-14'
- A nested div with class 'text-2xl mb-3'
- Render the Title component with text1 as 'YOUR' and text2 as 'CART'
- A nested div
- Map over the cartData array and render a div for each item with key, class 'py-4 border-t
border-b text-gray-700 grid grid-cols-[4fr_0.5fr_0.5fr] sm:grid-cols-[4fr_2fr_0.5fr] items-center gap-4'
- A nested div with class 'flex items-start gap-6'
- Render an image with class 'w-16 sm:w-20', src as the first element of productData.image,
and an empty alt attribute
- A nested div
- Render a paragraph with class 'text-xs sm:text-lg font-medium' containing the product name
- A nested div with class 'flex items-center gap-5 mt-2'
- Render a paragraph with the currency and product price
- Render a paragraph with class 'px-2 sm:px-3 sm:py-1 border bg-slate-50' containing the
item size
- Render an input with class 'border max-w-10 sm:max-w-20 px-1 sm:px-2 py-1', type 'number',
min 1, defaultValue as item quantity, and onChange event to update the quantity
- Render an image with class 'w-4 mr-4 sm:w-5 cursor-pointer', src as assets.bin_icon, and an
empty alt attribute, with an onClick event to update the quantity to 0
- A nested div with class 'flex justify-end my-20'
- A nested div with class 'w-full sm:w-[450px]'
- Render the CartTotal component
- A nested div with class 'w-full text-end'
- Render a button with class 'bg-black text-white text-sm my-8 px-8 py-3', onClick event to
navigate to '/place-order', and text 'PROCEED TO CHECKOUT'
5. Export the Cart component as the default export
Collection.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect, useState from 'react'
- ShopContext from '../context/ShopContext'
- assets from '../assets/assets'
- Title from '../components/Title'
- ProductItem from '../components/ProductItem'

2. Define the Collection component:


- Use the useContext hook to get products, search, and showSearch from ShopContext
- Initialize state variables: showFilter, filterProducts, category, subCategory, sortType

3. Define the toggleCategory function:


- Check if the category array includes the selected value
- If true, remove the value from the category array
- If false, add the value to the category array

4. Define the toggleSubCategory function:


- Check if the subCategory array includes the selected value
- If true, remove the value from the subCategory array
- If false, add the value to the subCategory array

5. Define the applyFilter function:


- Create a copy of the products array
- If showSearch and search are true, filter the productsCopy array based on the search term
- If category array has values, filter the productsCopy array based on the category
- If subCategory array has values, filter the productsCopy array based on the subCategory
- Set the filterProducts state with the filtered productsCopy array

6. Define the sortProduct function:


- Create a copy of the filterProducts array
- Sort the fpCopy array based on the sortType
- Set the filterProducts state with the sorted fpCopy array

7. Use the useEffect hook to apply filters when category, subCategory, search, showSearch, or
products change

8. Use the useEffect hook to sort products when sortType changes

9. Return the JSX structure:


- A div with class 'flex flex-col sm:flex-row gap-1 sm:gap-10 pt-10 border-t'
- A nested div with class 'min-w-60'
- Render a paragraph with class 'my-2 text-xl flex items-center cursor-pointer gap-2' with text
'FILTERS' and an image with class based on showFilter state
- A nested div with class based on showFilter state containing category filter options
- A nested div with class based on showFilter state containing subCategory filter options
- A nested div with class 'flex-1'
- A nested div with class 'flex justify-between text-base sm:text-2xl mb-4'
- Render the Title component with text1 as 'ALL' and text2 as 'COLLECTIONS'
- Render a select element with class 'border-2 border-gray-300 text-sm px-2' and onChange
event to setSortType
- A nested div with class 'grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 gap-y-6'
- Map over the filterProducts array and render a ProductItem component for each item with
key, name, id, price, and image props

10. Export the Collection component as the default export

Contact.jsx:-

1. Import necessary modules and components:


- React from 'react'
- Title from '../components/Title'
- assets from '../assets/assets'
- NewsletterBox from '../components/NewsletterBox'

2. Define the Contact component:

3. Return the JSX structure:


- A div
- A nested div with class 'text-center text-2xl pt-10 border-t'
- Render the Title component with text1 as 'CONTACT' and text2 as 'US'
- A nested div with class 'my-10 flex flex-col justify-center md:flex-row gap-10 mb-28'
- Render an image with class 'w-full md:max-w-[480px]', src as assets.contact_img, and an empty
alt attribute
- A nested div with class 'flex flex-col justify-center items-start gap-6'
- Render a paragraph with class 'font-semibold text-xl text-gray-600' with text 'Our Store'
- Render a paragraph with class 'text-gray-500' with the store address
- Render a paragraph with class 'text-gray-500' with the store contact information
- Render a paragraph with class 'font-semibold text-xl text-gray-600' with text 'Careers at
Forever'
- Render a paragraph with class 'text-gray-500' with text about careers
- Render a button with class 'border border-black px-8 py-4 text-sm hover:bg-black hover:text-
white transition-all duration-500' with text 'Explore Jobs'
- Render the NewsletterBox component

4. Export the Contact component as the default export

Home.jsx:-

1. Import necessary modules and components:


- React from 'react'
- Hero from '../components/Hero'
- LatestCollection from '../components/LatestCollection'
- BestSeller from '../components/BestSeller'
- OurPolicy from '../components/OurPolicy'
- NewsletterBox from '../components/NewsletterBox'

2. Define the Home component:


3. Return the JSX structure:
- A div
- Render the Hero component
- Render the LatestCollection component
- Render the BestSeller component
- Render the OurPolicy component
- Render the NewsletterBox component

4. Export the Home component as the default export

Login.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect, useState from 'react'
- ShopContext from '../context/ShopContext'
- axios from 'axios'
- toast from 'react-toastify'

2. Define the Login component:


- Initialize state variables: currentState, name, password, email
- Use the useContext hook to get token, setToken, navigate, and backendUrl from ShopContext

3. Define the onSubmitHandler function:


- Prevent the default form submission behavior
- If currentState is 'Sign Up':
- Send a POST request to register the user with name, email, and password
- If successful, set the token and store it in localStorage
- If an error occurs, show an error toast
- If currentState is 'Login':
- Send a POST request to log in the user with email and password
- If successful, set the token and store it in localStorage
- If an error occurs, show an error toast

4. Use the useEffect hook to navigate to the home page if token is present

5. Return the JSX structure:


- A form with onSubmit event set to onSubmitHandler and class 'flex flex-col items-center w-[90%]
sm:max-w-96 m-auto mt-14 gap-4 text-gray-800'
- A nested div with class 'inline-flex items-center gap-2 mb-2 mt-10'
- Render a paragraph with class 'prata-regular text-3xl' containing currentState
- Render a horizontal rule with class 'border-none h-[1.5px] w-8 bg-gray-800'
- If currentState is 'Sign Up', render an input for name with onChange event to update name, value
set to name, type 'text', class 'w-full px-3 py-2 border border-gray-800', placeholder 'Name', and
required attribute
- Render an input for email with onChange event to update email, value set to email, type 'email',
class 'w-full px-3 py-2 border border-gray-800', placeholder 'Email', and required attribute
- Render an input for password with onChange event to update password, value set to password,
type 'password', class 'w-full px-3 py-2 border border-gray-800', placeholder 'Password', and required
attribute
- A nested div with class 'w-full flex justify-between text-sm mt-[-8px]'
- Render a paragraph with text 'Forgot your password?' and class 'cursor-pointer'
- If currentState is 'Login', render a paragraph with text 'Create account' and class 'cursor-pointer'
with onClick event to set currentState to 'Sign Up'
- If currentState is 'Sign Up', render a paragraph with text 'Login Here' and class 'cursor-pointer'
with onClick event to set currentState to 'Login'
- Render a button with class 'bg-black text-white font-light px-8 py-2 mt-4' containing text based
on currentState

6. Export the Login component as the default export

Orders.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect, useState from 'react'
- ShopContext from '../context/ShopContext'
- Title from '../components/Title'
- axios from 'axios'

2. Define the Orders component:


- Use the useContext hook to get backendUrl, token, and currency from ShopContext
- Initialize a state variable orderData with an empty array using useState

3. Define the loadOrderData function:


- Check if token is present, if not, return null
- Send a POST request to fetch user orders with token in headers
- If successful, process the response data to extract order items and set the orderData state with
the processed data

4. Use the useEffect hook to load order data when the token changes

5. Return the JSX structure:


- A div with class 'border-t pt-16'
- A nested div with class 'text-2xl'
- Render the Title component with text1 as 'MY' and text2 as 'ORDERS'
- A nested div
- Map over the orderData array and render a div for each item with key, class 'py-4 border-t
border-b text-gray-700 flex flex-col md:flex-row md:items-center md:justify-between gap-4'
- A nested div with class 'flex items-start gap-6 text-sm'
- Render an image with class 'w-16 sm:w-20', src as the first element of item.image, and an
empty alt attribute
- A nested div
- Render a paragraph with class 'sm:text-base font-medium' containing the item name
- A nested div with class 'flex items-center gap-3 mt-1 text-base text-gray-700'
- Render a paragraph with the currency and item price
- Render a paragraph with text 'Quantity: ' and the item quantity
- Render a paragraph with text 'Size: ' and the item size
- Render a paragraph with class 'mt-1' containing the order date
- Render a paragraph with class 'mt-1' containing the payment method
- A nested div with class 'md:w-1/2 flex justify-between'
- A nested div with class 'flex items-center gap-2'
- Render a paragraph with class 'min-w-2 h-2 rounded-full bg-green-500'
- Render a paragraph with class 'text-sm md:text-base' containing the order status
- Render a button with class 'border px-4 py-2 text-sm font-medium rounded-sm' and onClick
event to loadOrderData with text 'Track Order'

6. Export the Orders component as the default export

PlaceOrder.jsx:-

1. Import necessary modules and components:


- React, useContext, useState from 'react'
- Title from '../components/Title'
- CartTotal from '../components/CartTotal'
- assets from '../assets/assets'
- ShopContext from '../context/ShopContext'
- axios from 'axios'
- toast from 'react-toastify'

2. Define the PlaceOrder component:


- Initialize state variables: method, formData
- Use the useContext hook to get navigate, backendUrl, token, cartItems, setCartItems,
getCartAmount, delivery_fee, and products from ShopContext

3. Define the onChangeHandler function:


- Update the formData state with the new input values

4. Define the initPay function:


- Create options for the Razorpay payment gateway
- Open the Razorpay payment gateway with the options

5. Define the onSubmitHandler function:


- Prevent the default form submission behavior
- Create an array of orderItems from cartItems
- Create an orderData object with address, items, and amount
- Send a POST request to place the order based on the selected payment method (COD, Stripe,
Razorpay)
- Handle the response and update the cartItems state and navigate to the orders page if successful

6. Return the JSX structure:


- A form with onSubmit event set to onSubmitHandler and class 'flex flex-col sm:flex-row justify-
between gap-4 pt-5 sm:pt-14 min-h-[80vh] border-t'
- A nested div with class 'flex flex-col gap-4 w-full sm:max-w-[480px]'
- Render the Title component with text1 as 'DELIVERY' and text2 as 'INFORMATION'
- Render input fields for firstName, lastName, email, street, city, state, zipcode, country, and
phone with onChange events to update formData
- A nested div with class 'mt-8'
- Render the CartTotal component
- Render the Title component with text1 as 'PAYMENT' and text2 as 'METHOD'
- Render payment method selection options (Stripe, Razorpay, COD) with onClick events to
update the method state
- Render a button with type 'submit' and class 'bg-black text-white px-16 py-3 text-sm' with text
'PLACE ORDER'
7. Export the PlaceOrder component as the default export

Product.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect, useState from 'react'
- useParams from 'react-router-dom'
- ShopContext from '../context/ShopContext'
- assets from '../assets/assets'
- RelatedProducts from '../components/RelatedProducts'

2. Define the Product component:


- Use the useParams hook to get the productId from the URL
- Use the useContext hook to get products, currency, and addToCart from ShopContext
- Initialize state variables: productData, image, size

3. Define the fetchProductData function:


- Loop through the products array and find the product with the matching productId
- Set the productData state with the found product
- Set the image state with the first image of the found product

4. Use the useEffect hook to fetch product data when productId or products change

5. Return the JSX structure:


- If productData is available, render the following:
- A div with class 'border-t-2 pt-10 transition-opacity ease-in duration-500 opacity-100'
- A nested div with class 'flex gap-12 sm:gap-12 flex-col sm:flex-row'
- A nested div with class 'flex-1 flex flex-col-reverse gap-3 sm:flex-row'
- A nested div with class 'flex sm:flex-col overflow-x-auto sm:overflow-y-scroll justify-between
sm:justify-normal sm:w-[18.7%] w-full'
- Map over the productData.image array and render an image for each item with onClick
event to setImage, src as item, key, class 'w-[24%] sm:w-full sm:mb-3 flex-shrink-0 cursor-pointer',
and an empty alt attribute
- A nested div with class 'w-full sm:w-[80%]'
- Render an image with class 'w-full h-auto', src as image, and an empty alt attribute
- A nested div with class 'flex-1'
- Render a heading with class 'font-medium text-2xl mt-2' containing the product name
- A nested div with class 'flex items-center gap-1 mt-2'
- Render star icons and a paragraph with the number of reviews
- Render a paragraph with class 'mt-5 text-3xl font-medium' containing the currency and
product price
- Render a paragraph with class 'mt-5 text-gray-500 md:w-4/5' containing the product
description
- A nested div with class 'flex flex-col gap-4 my-8'
- Render a paragraph with text 'Select Size'
- A nested div with class 'flex gap-2'
- Map over the productData.sizes array and render a button for each item with onClick event
to setSize, class based on the selected size, key, and text as item
- Render a button with onClick event to addToCart, class 'bg-black text-white px-8 py-3 text-sm
active:bg-gray-700', and text 'ADD TO CART'
- Render a horizontal rule with class 'mt-8 sm:w-4/5'
- A nested div with class 'text-sm text-gray-500 mt-5 flex flex-col gap-1'
- Render paragraphs with product information
- A nested div with class 'mt-20'
- A nested div with class 'flex'
- Render a bold paragraph with class 'border px-5 py-3 text-sm' with text 'Description'
- Render a paragraph with class 'border px-5 py-3 text-sm' with text 'Reviews (122)'
- A nested div with class 'flex flex-col gap-4 border px-6 py-6 text-sm text-gray-500'
- Render paragraphs with description text
- Render the RelatedProducts component with category and subCategory props from
productData
- If productData is not available, render a div with class 'opacity-0'

6. Export the Product component as the default export

Verify.jsx:-

1. Import necessary modules and components:


- React, useContext, useEffect from 'react'
- ShopContext from '../context/ShopContext'
- useSearchParams from 'react-router-dom'
- toast from 'react-toastify'
- axios from 'axios'

2. Define the Verify component:


- Use the useContext hook to get navigate, token, setCartItems, and backendUrl from ShopContext
- Use the useSearchParams hook to get searchParams and setSearchParams
- Get the success and orderId parameters from searchParams

3. Define the verifyPayment function:


- Check if token is present, if not, return null
- Send a POST request to verify the payment with success and orderId parameters, and token in
headers
- If successful, clear the cartItems state and navigate to the orders page
- If not successful, navigate to the cart page
- Handle any errors by logging them and showing an error toast

4. Use the useEffect hook to call verifyPayment when the token changes

5. Return the JSX structure:


- A div (empty for now)

6. Export the Verify component as the default export

src:-
App.jsx:-

1. Import necessary modules and components:


- React from 'react'
- Routes, Route from 'react-router-dom'
- Home from './pages/Home'
- Collection from './pages/Collection'
- About from './pages/About'
- Contact from './pages/Contact'
- Product from './pages/Product'
- Cart from './pages/Cart'
- Login from './pages/Login'
- PlaceOrder from './pages/PlaceOrder'
- Orders from './pages/Orders'
- Navbar from './components/Navbar'
- Footer from './components/Footer'
- SearchBar from './components/SearchBar'
- ToastContainer, toast from 'react-toastify'
- 'react-toastify/dist/ReactToastify.css'
- Verify from './pages/Verify'

2. Define the App component:

3. Return the JSX structure:


- A div with class 'px-4 sm:px-[5vw] md:px-[7vw] lg:px-[9vw]'
- Render the ToastContainer component
- Render the Navbar component
- Render the SearchBar component
- Render the Routes component containing Route components for each page:
- Route for path '/' with element Home
- Route for path '/collection' with element Collection
- Route for path '/about' with element About
- Route for path '/contact' with element Contact
- Route for path '/product/:productId' with element Product
- Route for path '/cart' with element Cart
- Route for path '/login' with element Login
- Route for path '/place-order' with element PlaceOrder
- Route for path '/orders' with element Orders
- Route for path '/verify' with element Verify
- Render the Footer component

4. Export the App component as the default export

Main.jsx:-

1. Import necessary modules and components:


- React from 'react'
- ReactDOM from 'react-dom/client'
- App from './App.jsx'
- './index.css'
- BrowserRouter from 'react-router-dom'
- ShopContextProvider from './context/ShopContext.jsx'

2. Use ReactDOM.createRoot to create a root element:


- Get the root element by its ID 'root'

3. Render the App component wrapped with BrowserRouter and ShopContextProvider:


- Use BrowserRouter to wrap the ShopContextProvider
- Use ShopContextProvider to wrap the App component

4. Export the rendered component as the default export

Admin Panel:-
Components:-
Login.jsx:-

1. Import necessary modules and components:


- axios from 'axios'
- React, useState from 'react'
- backendUrl from '../App'
- toast from 'react-toastify'

2. Define the Login component:


- Initialize state variables: email, password
- Define the onSubmitHandler function:
- Prevent the default form submission behavior
- Send a POST request to the backend with email and password
- If successful, set the token
- If an error occurs, show an error toast

3. Return the JSX structure:


- A div with class 'min-h-screen flex items-center justify-center w-full'
- A nested div with class 'bg-white shadow-md rounded-lg px-8 py-6 max-w-md'
- Render a heading with class 'text-2xl font-bold mb-4' with text 'Admin Panel'
- Render a form with onSubmit event set to onSubmitHandler
- A nested div with class 'mb-3 min-w-72'
- Render a paragraph with class 'text-sm font-medium text-gray-700 mb-2' with text 'Email
Address'
- Render an input with onChange event to update email, value set to email, class 'rounded-md
w-full px-3 py-2 border border-gray-300 outline-none', type 'email', placeholder 'your@email.com',
and required attribute
- A nested div with class 'mb-3 min-w-72'
- Render a paragraph with class 'text-sm font-medium text-gray-700 mb-2' with text 'Password'
- Render an input with onChange event to update password, value set to password, class
'rounded-md w-full px-3 py-2 border border-gray-300 outline-none', type 'password', placeholder
'Enter your password', and required attribute
- Render a button with class 'mt-2 w-full py-2 px-4 rounded-md text-white bg-black', type
'submit', and text 'Login'

4. Export the Login component as the default export

Navbar.jsx:-

1. Import necessary modules and components:


- React from 'react'
- assets from '../assets/assets'

2. Define the Navbar component:


- Destructure setToken from the component's props
3. Return the JSX structure:
- A div with class 'flex items-center py-2 px-[4%] justify-between'
- Render an image with class 'w-[max(10%,80px)]', src as assets.logo, and an empty alt attribute
- Render a button with onClick event to setToken to an empty string, class 'bg-gray-600 text-white
px-5 py-2 sm:px-7 sm:py-2 rounded-full text-xs sm:text-sm', and text 'Logout'

4. Export the Navbar component as the default export

Sidebar.jsx:-

1. Import necessary modules and components:


- React from 'react'
- NavLink from 'react-router-dom'
- assets from '../assets/assets'

2. Define the Sidebar component:

3. Return the JSX structure:


- A div with class 'w-[18%] min-h-screen border-r-2'
- A nested div with class 'flex flex-col gap-4 pt-6 pl-[20%] text-[15px]'
- Render a NavLink to '/add' with class 'flex items-center gap-3 border border-gray-300 border-r-0
px-3 py-2 rounded-l'
- Render an image with class 'w-5 h-5', src as assets.add_icon, and an empty alt attribute
- Render a paragraph with class 'hidden md:block' with text 'Add Items'
- Render a NavLink to '/list' with class 'flex items-center gap-3 border border-gray-300 border-r-0
px-3 py-2 rounded-l'
- Render an image with class 'w-5 h-5', src as assets.order_icon, and an empty alt attribute
- Render a paragraph with class 'hidden md:block' with text 'List Items'
- Render a NavLink to '/orders' with class 'flex items-center gap-3 border border-gray-300 border-
r-0 px-3 py-2 rounded-l'
- Render an image with class 'w-5 h-5', src as assets.order_icon, and an empty alt attribute
- Render a paragraph with class 'hidden md:block' with text 'Orders'

4. Export the Sidebar component as the default export

Pages:-
Add.jsx:-

1. Import necessary modules and components:


- React, useState from 'react'
- assets from '../assets/assets'
- axios from 'axios'
- backendUrl from '../App'
- toast from 'react-toastify'

2. Define the Add component:


- Destructure token from the component's props
- Initialize state variables: image1, image2, image3, image4, name, description, price, category,
subCategory, bestseller, sizes
3. Define the onSubmitHandler function:
- Prevent the default form submission behavior
- Create a new FormData object
- Append name, description, price, category, subCategory, bestseller, sizes, and images to the
FormData object
- Send a POST request to add the product with the FormData object and token in headers
- If successful, show a success toast and reset the form fields
- If an error occurs, show an error toast

4. Return the JSX structure:


- A form with onSubmit event set to onSubmitHandler and class 'flex flex-col w-full items-start gap-
3'
- A nested div for image upload with class 'flex gap-2'
- Render labels and inputs for image1, image2, image3, and image4 with onChange events to
update the respective state variables
- A nested div for product name with class 'w-full'
- Render a paragraph with text 'Product name'
- Render an input for name with onChange event to update name, value set to name, class 'w-full
max-w-[500px] px-3 py-2', type 'text', placeholder 'Type here', and required attribute
- A nested div for product description with class 'w-full'
- Render a paragraph with text 'Product description'
- Render a textarea for description with onChange event to update description, value set to
description, class 'w-full max-w-[500px] px-3 py-2', type 'text', placeholder 'Write content here', and
required attribute
- A nested div for product category, sub category, and price with class 'flex flex-col sm:flex-row
gap-2 w-full sm:gap-8'
- Render a select element for category with onChange event to update category, class 'w-full px-3
py-2'
- Render a select element for subCategory with onChange event to update subCategory, class 'w-
full px-3 py-2'
- Render an input for price with onChange event to update price, value set to price, class 'w-full
px-3 py-2 sm:w-[120px]', type 'Number', placeholder '25'
- A nested div for product sizes with class 'flex gap-3'
- Render divs and paragraphs for sizes S, M, L, XL, and XXL with onClick events to update the sizes
state
- A nested div for bestseller checkbox with class 'flex gap-2 mt-2'
- Render an input for bestseller with onChange event to update bestseller, checked attribute set
to bestseller, type 'checkbox', id 'bestseller'
- Render a label for bestseller with text 'Add to bestseller'
- Render a button with type 'submit', class 'w-28 py-3 mt-4 bg-black text-white', and text 'ADD'

5. Export the Add component as the default export

List.jsx:-

1. Import necessary modules and components:


- axios from 'axios'
- React, useEffect, useState from 'react'
- backendUrl, currency from '../App'
- toast from 'react-toastify'
2. Define the List component:
- Destructure token from the component's props
- Initialize a state variable list with an empty array using useState

3. Define the fetchList function:


- Send a GET request to fetch the product list from the backend
- If successful, set the list state with the fetched products in reverse order
- If an error occurs, show an error toast

4. Define the removeProduct function:


- Send a POST request to remove a product with the given id and token in headers
- If successful, show a success toast and fetch the updated product list
- If an error occurs, show an error toast

5. Use the useEffect hook to fetch the product list on component mount

6. Return the JSX structure:


- A fragment
- Render a paragraph with class 'mb-2' with text 'All Products List'
- A nested div with class 'flex flex-col gap-2'
- Render a div with class 'hidden md:grid grid-cols-[1fr_3fr_1fr_1fr_1fr] items-center py-1 px-2
border bg-gray-100 text-sm' containing table headers
- Map over the list array and render a div for each item with key, class 'grid grid-cols-[1fr_3fr_1fr]
md:grid-cols-[1fr_3fr_1fr_1fr_1fr] items-center gap-2 py-1 px-2 border text-sm'
- Render an image with class 'w-12', src as the first element of item.image, and an empty alt
attribute
- Render a paragraph with the item name
- Render a paragraph with the item category
- Render a paragraph with the currency and item price
- Render a paragraph with class 'text-right md:text-center cursor-pointer text-lg' and onClick
event to remove the product with text 'X'

7. Export the List component as the default export

Orders.jsx:-

import React from 'react'


import { useEffect } from 'react'
import { useState } from 'react'
import axios from 'axios'
import { backendUrl, currency } from '../App'
import { toast } from 'react-toastify'
import { assets } from '../assets/assets'

const Orders = ({ token }) => {

const [orders, setOrders] = useState([])

const fetchAllOrders = async () => {

if (!token) {
return null;
}

try {

const response = await axios.post(backendUrl + '/api/order/list', {}, { headers: { token } })


if (response.data.success) {
setOrders(response.data.orders.reverse())
} else {
toast.error(response.data.message)
}

} catch (error) {
toast.error(error.message)
}

const statusHandler = async ( event, orderId ) => {


try {
const response = await axios.post(backendUrl + '/api/order/status' , {orderId,
status:event.target.value}, { headers: {token}})
if (response.data.success) {
await fetchAllOrders()
}
} catch (error) {
console.log(error)
toast.error(response.data.message)
}
}

useEffect(() => {
fetchAllOrders();
}, [token])

return (
<div>
<h3>Order Page</h3>
<div>
{
orders.map((order, index) => (
<div className='grid grid-cols-1 sm:grid-cols-[0.5fr_2fr_1fr] lg:grid-cols-
[0.5fr_2fr_1fr_1fr_1fr] gap-3 items-start border-2 border-gray-200 p-5 md:p-8 my-3 md:my-4 text-xs
sm:text-sm text-gray-700' key={index}>
<img className='w-12' src={assets.parcel_icon} alt="" />
<div>
<div>
{order.items.map((item, index) => {
if (index === order.items.length - 1) {
return <p className='py-0.5' key={index}> {item.name} x {item.quantity} <span>
{item.size} </span> </p>
}
else {
return <p className='py-0.5' key={index}> {item.name} x {item.quantity} <span>
{item.size} </span> ,</p>
}
})}
</div>
<p className='mt-3 mb-2 font-medium'>{order.address.firstName + " " +
order.address.lastName}</p>
<div>
<p>{order.address.street + ","}</p>
<p>{order.address.city + ", " + order.address.state + ", " + order.address.country + ", " +
order.address.zipcode}</p>
</div>
<p>{order.address.phone}</p>
</div>
<div>
<p className='text-sm sm:text-[15px]'>Items : {order.items.length}</p>
<p className='mt-3'>Method : {order.paymentMethod}</p>
<p>Payment : { order.payment ? 'Done' : 'Pending' }</p>
<p>Date : {new Date(order.date).toLocaleDateString()}</p>
</div>
<p className='text-sm sm:text-[15px]'>{currency}{order.amount}</p>
<select onChange={(event)=>statusHandler(event,order._id)} value={order.status}
className='p-2 font-semibold'>
<option value="Order Placed">Order Placed</option>
<option value="Packing">Packing</option>
<option value="Shipped">Shipped</option>
<option value="Out for delivery">Out for delivery</option>
<option value="Delivered">Delivered</option>
</select>
</div>
))
}
</div>
</div>
)
}

export default Orders

src:-
App.jsx:-

1. Import necessary modules and components:


- React, useEffect, useState from 'react'
- Navbar from './components/Navbar'
- Sidebar from './components/Sidebar'
- Routes, Route from 'react-router-dom'
- Add from './pages/Add'
- List from './pages/List'
- Orders from './pages/Orders'
- Login from './components/Login'
- ToastContainer from 'react-toastify'
- 'react-toastify/dist/ReactToastify.css'

2. Define the backendUrl and currency constants:


- backendUrl from import.meta.env.VITE_BACKEND_URL
- currency as '$'

3. Define the App component:


- Initialize a state variable token with the value from localStorage or an empty string using useState
- Use the useEffect hook to update localStorage with the token whenever it changes

4. Return the JSX structure:


- A div with class 'bg-gray-50 min-h-screen'
- Render the ToastContainer component
- Conditionally render the Login component if token is an empty string, passing setToken as a prop
- If token is not an empty string, render the following:
- Render the Navbar component, passing setToken as a prop
- Render a horizontal rule
- A nested div with class 'flex w-full'
- Render the Sidebar component
- A nested div with class 'w-[70%] mx-auto ml-[max(5vw,25px)] my-8 text-gray-600 text-base'
- Render the Routes component containing Route components for each page:
- Route for path '/add' with element Add, passing token as a prop
- Route for path '/list' with element List, passing token as a prop
- Route for path '/orders' with element Orders, passing token as a prop

5. Export the App component as the default export

main.jsx:-

1. Import necessary modules and components:


- React from 'react'
- ReactDOM from 'react-dom/client'
- App from './App.jsx'
- './index.css'
- BrowserRouter from 'react-router-dom'

2. Use ReactDOM.createRoot to create a root element:


- Get the root element by its ID 'root'

3. Render the App component wrapped with BrowserRouter:


- Use BrowserRouter to wrap the App component

4. Export the rendered component as the default export


backend:-
config:-
cloudinary.js:-

1. Import the cloudinary module:


- Import the v2 version of cloudinary from "cloudinary"

2. Define the connectCloudinary function:


- Use the async keyword to define an asynchronous function

3. Configure Cloudinary:
- Call the cloudinary.config method with an object containing the following properties:
- cloud_name: Set to the value of process.env.CLOUDINARY_NAME
- api_key: Set to the value of process.env.CLOUDINARY_API_KEY
- api_secret: Set to the value of process.env.CLOUDINARY_SECRET_KEY

4. Export the connectCloudinary function as the default export

Mongodb.js:-

1. Import the mongoose module:


- Import mongoose from "mongoose"

2. Define the connectDB function:


- Use the async keyword to define an asynchronous function

3. Set up a connection event listener:


- Use mongoose.connection.on to listen for the 'connected' event
- Log "DB Connected" to the console when the event is triggered

4. Connect to the MongoDB database:


- Use mongoose.connect with the MongoDB URI from the environment variable
process.env.MONGODB_URI and append "/e-commerce" to the URI

5. Export the connectDB function as the default export

controllers:-
cartController.js:-

1. Import the userModel module:


- Import userModel from "../models/userModel.js"

2. Define the addToCart function:


- Use the async keyword to define an asynchronous function
- Extract userId, itemId, and size from req.body
- Find the user by userId using userModel.findById
- Get the user's cartData
- Check if the itemId exists in cartData
- If true, check if the size exists in cartData[itemId]
- If true, increment the quantity by 1
- If false, set the quantity to 1
- If false, create a new entry for itemId and set the quantity to 1
- Update the user's cartData using userModel.findByIdAndUpdate
- Send a JSON response with success as true and message as "Added To Cart"
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

3. Define the updateCart function:


- Use the async keyword to define an asynchronous function
- Extract userId, itemId, size, and quantity from req.body
- Find the user by userId using userModel.findById
- Get the user's cartData
- Update the quantity for the specified itemId and size in cartData
- Update the user's cartData using userModel.findByIdAndUpdate
- Send a JSON response with success as true and message as "Cart Updated"
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

4. Define the getUserCart function:


- Use the async keyword to define an asynchronous function
- Extract userId from req.body
- Find the user by userId using userModel.findById
- Get the user's cartData
- Send a JSON response with success as true and cartData
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

5. Export the functions:


- Export addToCart, updateCart, and getUserCart

orderController.js:-

1. Import necessary modules and components:


- orderModel from "../models/orderModel.js"
- userModel from "../models/userModel.js"
- Stripe from 'stripe'
- razorpay from 'razorpay'

2. Define global variables:


- currency as 'inr'
- deliveryCharge as 10

3. Initialize payment gateways:


- Create a new Stripe instance with the secret key from environment variables
- Create a new razorpay instance with key_id and key_secret from environment variables

4. Define the placeOrder function for COD method:


- Extract userId, items, amount, and address from req.body
- Create an orderData object with the extracted data, paymentMethod as "COD", payment as false,
and date as the current date
- Create a new orderModel instance with orderData and save it
- Update the user's cartData to an empty object
- Send a JSON response with success as true and message as "Order Placed"
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

5. Define the placeOrderStripe function for Stripe method:


- Extract userId, items, amount, and address from req.body
- Extract origin from req.headers
- Create an orderData object with the extracted data, paymentMethod as "Stripe", payment as
false, and date as the current date
- Create a new orderModel instance with orderData and save it
- Create line_items array with price_data for each item and delivery charges
- Create a Stripe checkout session with success_url, cancel_url, line_items, and mode as 'payment'
- Send a JSON response with success as true and session_url as the session URL
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

6. Define the verifyStripe function:


- Extract orderId, success, and userId from req.body
- If success is "true", update the order's payment status to true and clear the user's cartData
- If success is "false", delete the order
- Send a JSON response with success as true or false
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

7. Define the placeOrderRazorpay function for Razorpay method:


- Extract userId, items, amount, and address from req.body
- Create an orderData object with the extracted data, paymentMethod as "Razorpay", payment as
false, and date as the current date
- Create a new orderModel instance with orderData and save it
- Create options object with amount, currency, and receipt as the order ID
- Create a Razorpay order with the options
- Send a JSON response with success as true and the order
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

8. Define the verifyRazorpay function:


- Extract userId and razorpay_order_id from req.body
- Fetch the order information from Razorpay
- If the order status is 'paid', update the order's payment status to true and clear the user's
cartData
- If the order status is not 'paid', send a JSON response with success as false and message as
'Payment Failed'
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

9. Define the allOrders function for Admin Panel:


- Fetch all orders from the orderModel
- Send a JSON response with success as true and the orders
- Handle any errors by logging them and sending a JSON response with success as false and the
error message
10. Define the userOrders function for Frontend:
- Extract userId from req.body
- Fetch orders for the user from the orderModel
- Send a JSON response with success as true and the orders
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

11. Define the updateStatus function for Admin Panel:


- Extract orderId and status from req.body
- Update the order's status in the orderModel
- Send a JSON response with success as true and message as 'Status Updated'
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

12. Export the functions:


- Export verifyRazorpay, verifyStripe, placeOrder, placeOrderStripe, placeOrderRazorpay, allOrders,
userOrders, updateStatus

productController.js:-

1. Import necessary modules and components:


- cloudinary from "cloudinary"
- productModel from "../models/productModel.js"

2. Define the addProduct function:


- Use the async keyword to define an asynchronous function
- Extract name, description, price, category, subCategory, sizes, and bestseller from req.body
- Extract image1, image2, image3, and image4 from req.files
- Filter out undefined images and store them in the images array
- Upload each image to Cloudinary and get the secure URLs using Promise.all
- Create a productData object with the extracted data, parsed sizes, and image URLs
- Create a new productModel instance with productData and save it
- Send a JSON response with success as true and message as "Product Added"
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

3. Define the listProducts function:


- Use the async keyword to define an asynchronous function
- Fetch all products from the productModel
- Send a JSON response with success as true and the products
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

4. Define the removeProduct function:


- Use the async keyword to define an asynchronous function
- Delete the product by its ID from req.body using productModel.findByIdAndDelete
- Send a JSON response with success as true and message as "Product Removed"
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

5. Define the singleProduct function:


- Use the async keyword to define an asynchronous function
- Extract productId from req.body
- Fetch the product by its ID using productModel.findById
- Send a JSON response with success as true and the product
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

6. Export the functions:


- Export listProducts, addProduct, removeProduct, and singleProduct

userControler.js:-

1. Import necessary modules and components:


- validator from "validator"
- bcrypt from "bcrypt"
- jwt from 'jsonwebtoken'
- userModel from "../models/userModel.js"

2. Define the createToken function:


- Use jwt.sign to create a token with the user ID and the secret key from environment variables

3. Define the loginUser function:


- Use the async keyword to define an asynchronous function
- Extract email and password from req.body
- Find the user by email using userModel.findOne
- If the user does not exist, send a JSON response with success as false and message as "User
doesn't exist"
- Compare the provided password with the user's hashed password using bcrypt.compare
- If the passwords match, create a token and send a JSON response with success as true and the
token
- If the passwords do not match, send a JSON response with success as false and message as
"Invalid credentials"
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

4. Define the registerUser function:


- Use the async keyword to define an asynchronous function
- Extract name, email, and password from req.body
- Check if the user already exists by email using userModel.findOne
- If the user exists, send a JSON response with success as false and message as "User already exists"
- Validate the email format using validator.isEmail
- If the email is not valid, send a JSON response with success as false and message as "Please enter
a valid email"
- Check if the password length is less than 8 characters
- If the password is not strong, send a JSON response with success as false and message as "Please
enter a strong password"
- Hash the password using bcrypt.genSalt and bcrypt.hash
- Create a new userModel instance with the provided data and hashed password
- Save the new user and create a token
- Send a JSON response with success as true and the token
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

5. Define the adminLogin function:


- Use the async keyword to define an asynchronous function
- Extract email and password from req.body
- Check if the email and password match the admin credentials from environment variables
- If the credentials match, create a token and send a JSON response with success as true and the
token
- If the credentials do not match, send a JSON response with success as false and message as
"Invalid credentials"
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

6. Export the functions:


- Export loginUser, registerUser, and adminLogin

middleware:-
adminAuth.js:-

1. Import the jwt module:


- Import jwt from 'jsonwebtoken'

2. Define the adminAuth middleware function:


- Use the async keyword to define an asynchronous function
- Extract the token from req.headers
- If the token is not present, send a JSON response with success as false and message as "Not
Authorized Login Again"
- Verify the token using jwt.verify with the secret key from environment variables
- If the decoded token does not match the concatenation of ADMIN_EMAIL and
ADMIN_PASSWORD from environment variables, send a JSON response with success as false and
message as "Not Authorized Login Again"
- If the token is valid, call the next middleware function
- Handle any errors by logging them and sending a JSON response with success as false and the
error message

3. Export the adminAuth function as the default export

auth.js:-

1. Import the jwt module:


- Import jwt from 'jsonwebtoken'

2. Define the authUser middleware function:


- Use the async keyword to define an asynchronous function
- Extract the token from req.headers
- If the token is not present, send a JSON response with success as false and message as 'Not
Authorized Login Again'
- Try to verify the token using jwt.verify with the secret key from environment variables
- If the token is valid, set req.body.userId to the decoded token's id and call the next middleware
function
- If an error occurs, log the error and send a JSON response with success as false and the error
message

3. Export the authUser function as the default export

multer.js:-
1. Import the multer module:
- Import multer from "multer"

2. Define the storage configuration:


- Use multer.diskStorage to create a storage configuration object
- Define the filename function to set the filename of the uploaded file
- The function takes req, file, and callback as parameters
- Call the callback function with null and file.originalname to set the filename to the original name
of the uploaded file

3. Create the upload middleware:


- Use multer with the storage configuration to create the upload middleware

4. Export the upload middleware as the default export

models:-
orderModel.js:-

1. Import the mongoose module:


- Import mongoose from 'mongoose'

2. Define the orderSchema:


- Create a new mongoose.Schema object with the following fields:
- userId: { type: String, required: true }
- items: { type: Array, required: true }
- amount: { type: Number, required: true }
- address: { type: Object, required: true }
- status: { type: String, required: true, default: 'Order Placed' }
- paymentMethod: { type: String, required: true }
- payment: { type: Boolean, required: true, default: false }
- date: { type: Number, required: true }

3. Define the orderModel:


- Use mongoose.models.order if it exists, otherwise create a new mongoose.model with the name
'order' and the orderSchema

4. Export the orderModel as the default export

productModel.js:-

1. Import the mongoose module:


- Import mongoose from "mongoose"

2. Define the productSchema:


- Create a new mongoose.Schema object with the following fields:
- name: { type: String, required: true }
- description: { type: String, required: true }
- price: { type: Number, required: true }
- image: { type: Array, required: true }
- category: { type: String, required: true }
- subCategory: { type: String, required: true }
- sizes: { type: Array, required: true }
- bestseller: { type: Boolean }
- date: { type: Number, required: true }

3. Define the productModel:


- Use mongoose.models.product if it exists, otherwise create a new mongoose.model with the
name 'product' and the productSchema

4. Export the productModel as the default export

userModel.js:-

1. Import the mongoose module:


- Import mongoose from "mongoose"

2. Define the userSchema:


- Create a new mongoose.Schema object with the following fields:
- name: { type: String, required: true }
- email: { type: String, required: true, unique: true }
- password: { type: String, required: true }
- cartData: { type: Object, default: {} }
- Set the minimize option to false

3. Define the userModel:


- Use mongoose.models.user if it exists, otherwise create a new mongoose.model with the name
'user' and the userSchema

4. Export the userModel as the default export

routes:-
cartRoute.js:-

1. Import necessary modules and components:


- Import express from 'express'
- Import addToCart, getUserCart, and updateCart from '../controllers/cartController.js'
- Import authUser from '../middleware/auth.js'

2. Create a new router instance:


- Use express.Router() to create a new router instance and assign it to cartRouter

3. Define routes for the cartRouter:


- Define a POST route for '/get' with authUser middleware and getUserCart controller
- Define a POST route for '/add' with authUser middleware and addToCart controller
- Define a POST route for '/update' with authUser middleware and updateCart controller
4. Export the cartRouter as the default export

orderRoute.js:-

1. Import necessary modules and components:


- Import express from 'express'
- Import placeOrder, placeOrderStripe, placeOrderRazorpay, allOrders, userOrders, updateStatus,
verifyStripe, verifyRazorpay from '../controllers/orderController.js'
- Import adminAuth from '../middleware/adminAuth.js'
- Import authUser from '../middleware/auth.js'

2. Create a new router instance:


- Use express.Router() to create a new router instance and assign it to orderRouter

3. Define routes for the orderRouter:


- Admin Features:
- Define a POST route for '/list' with adminAuth middleware and allOrders controller
- Define a POST route for '/status' with adminAuth middleware and updateStatus controller
- Payment Features:
- Define a POST route for '/place' with authUser middleware and placeOrder controller
- Define a POST route for '/stripe' with authUser middleware and placeOrderStripe controller
- Define a POST route for '/razorpay' with authUser middleware and placeOrderRazorpay
controller
- User Feature:
- Define a POST route for '/userorders' with authUser middleware and userOrders controller
- Verify Payment:
- Define a POST route for '/verifyStripe' with authUser middleware and verifyStripe controller
- Define a POST route for '/verifyRazorpay' with authUser middleware and verifyRazorpay
controller

4. Export the orderRouter as the default export

productRoute.js:-

1. Import necessary modules and components:


- Import express from 'express'
- Import listProducts, addProduct, removeProduct, singleProduct from
'../controllers/productController.js'
- Import upload from '../middleware/multer.js'
- Import adminAuth from '../middleware/adminAuth.js'

2. Create a new router instance:


- Use express.Router() to create a new router instance and assign it to productRouter

3. Define routes for the productRouter:


- Define a POST route for '/add' with adminAuth middleware, upload middleware for handling
image uploads, and addProduct controller
- Define a POST route for '/remove' with adminAuth middleware and removeProduct controller
- Define a POST route for '/single' with singleProduct controller
- Define a GET route for '/list' with listProducts controller
4. Export the productRouter as the default export

userRoute.js:-

1. Import necessary modules and components:


- Import express from 'express'
- Import loginUser, registerUser, and adminLogin from '../controllers/userController.js'

2. Create a new router instance:


- Use express.Router() to create a new router instance and assign it to userRouter

3. Define routes for the userRouter:


- Define a POST route for '/register' with registerUser controller
- Define a POST route for '/login' with loginUser controller
- Define a POST route for '/admin' with adminLogin controller

4. Export the userRouter as the default export

Server.js:-

1. Import necessary modules and components:


- Import express from 'express'
- Import cors from 'cors'
- Import 'dotenv/config'
- Import connectDB from './config/mongodb.js'
- Import connectCloudinary from './config/cloudinary.js'
- Import userRouter from './routes/userRoute.js'
- Import productRouter from './routes/productRoute.js'
- Import cartRouter from './routes/cartRoute.js'
- Import orderRouter from './routes/orderRoute.js'

2. App Configuration:
- Create an express application instance and assign it to app
- Define the port variable using process.env.PORT or default to 4000
- Call connectDB() to connect to the MongoDB database
- Call connectCloudinary() to connect to Cloudinary

3. Middlewares:
- Use express.json() middleware to parse JSON request bodies
- Use cors() middleware to enable Cross-Origin Resource Sharing

4. API Endpoints:
- Use '/api/user' route with userRouter
- Use '/api/product' route with productRouter
- Use '/api/cart' route with cartRouter
- Use '/api/order' route with orderRouter

5. Root Endpoint:
- Define a GET route for '/' that sends "API Working" as the response

6. Start the Server:


- Listen on the defined port and log a message indicating the server has started

You might also like