Skip to content
  • Unlock Pro
  • Log in with GitHub
Solution
Submitted 5 months ago

Product list with cart using React

react, styled-components
Snigdha Sukun•550
@snigdha-sukun
A solution to the Product list with cart challenge
View live sitePreview (opens in new tab)View codeCode (opens in new tab)

Solution retrospective


What are you most proud of, and what would you do differently next time?

I am proud of learning how to create & use React Context & Provider:

interface CartContextType {
 products: Product[];
 cart: CartItemType[];
 addToCart: (product: Product) => void;
 removeFromCart: (productId: number) => void;
 emptyCart: () => void;
 findCartItem: (productId: number) => CartItemType | undefined;
 reduceQty: (product: Product) => void;
 increaseQty: (product: Product) => void;
 getTotalCost: () => number;
 isModalOpen: boolean;
 openModal: () => void;
 closeModal: () => void;
 resetCart: () => void;
}

export const CartContext = createContext<CartContextType | undefined>(
 undefined,
);


export const CartProvider: React.FC<{ children: React.ReactNode }> = ({
 children,
}) => {
 const { products } = useFetchProducts();

 const [cart, setCart] = useState<CartItemType[]>([]);
 const [isModalOpen, setIsModalOpen] = useState(false);

 const openModal = useCallback(() => setIsModalOpen(true), []);
 const closeModal = useCallback(() => setIsModalOpen(false), []);

 const resetCart = useCallback(() => {
  setCart([]);
  closeModal();
 }, [closeModal]);

 const addToCart = useCallback((product: Product) => {
  setCart((prevCart) => {
   return [...prevCart, { ...product, quantity: 1 }];
  });
 }, []);

 const increaseQty = useCallback((product: Product) => {
  setCart((prevCart) => {
   return prevCart.map((item) =>
    item.id === product.id
     ? { ...item, quantity: item.quantity + 1 }
     : item,
   );
  });
 }, []);

 const reduceQty = useCallback((product: Product) => {
  setCart((prevCart) => {
   const updatedCart = prevCart
    .map((item) => {
     if (item.id === product.id) {
      const qty = item.quantity;
      if (qty === 1) {
       return null;
      }
      return { ...item, quantity: item.quantity - 1 };
     }
     return item;
    })
    .filter((item): item is CartItemType => item !== null);
   return updatedCart;
  });
 }, []);

 const removeFromCart = useCallback((productId: number) => {
  setCart((prevCart) => prevCart.filter((item) => item.id !== productId));
 }, []);

 const emptyCart = useCallback(() => {
  setCart([]);
 }, []);

 const findCartItem = useCallback(
  (productId: number) => {
   return cart.find((item) => item.id === productId);
  },
  [cart],
 );

 const getTotalCost = useCallback(() => {
  return cart.reduce((acc, item) => acc + item.price * item.quantity, 0);
 }, [cart]);

 const contextValue = useMemo(
  () => ({
   products,
   cart,
   addToCart,
   removeFromCart,
   emptyCart,
   findCartItem,
   reduceQty,
   increaseQty,
   getTotalCost,
   isModalOpen,
   openModal,
   closeModal,
   resetCart,
  }),
  [
   products,
   cart,
   addToCart,
   removeFromCart,
   emptyCart,
   findCartItem,
   reduceQty,
   increaseQty,
   getTotalCost,
   isModalOpen,
   openModal,
   closeModal,
   resetCart,
  ],
 );

 return (
  <CartContext.Provider value={contextValue}>{children}</CartContext.Provider>
 );
};
export const useCart = () => {
 const context = useContext(CartContext);
 if (!context) {
  throw new Error("useCart must be used within a CartProvider");
 }
 return context;
};
function App() {

 return (
  <ThemeProvider theme={theme}>
   <CartProvider>
    <GlobalStyles />
    <Container>
     <ProductList />
     <Cart />
    </Container>
    <OrderDialog />
   </CartProvider>
  </ThemeProvider>
 );
}
What specific areas of your project would you like help with?

I still struggle with positioning certain UI elements. Like The "Add to Cart Button" in this challenge. Any tips or resources for learning that would be great!

Code
Select a file

Please log in to post a comment

Log in with GitHub

Community feedback

  • Pai-Kai Lee•320
    @PaiKai-Lee
    Posted 3 months ago

    Your project structure and design are excellent — I’ve learned a lot from your work.

    1. You made great use of useCallback and useMemo in the context to optimize re-renders and avoid unnecessary computations.
    2. Separating the hooks and provider made the structure much cleaner and easier to maintain.

Join our Discord community

Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!

Join our Discord

Stay up to datewith new challenges, featured solutions, selected articles, and our latest news

Frontend Mentor

  • Unlock Pro
  • Contact us
  • FAQs
  • Become a partner

Explore

  • Learning paths
  • Challenges
  • Solutions
  • Articles

Community

  • Discord
  • Guidelines

For companies

  • Hire developers
  • Train developers
© Frontend Mentor 2019 - 2025
  • Terms
  • Cookie Policy
  • Privacy Policy
  • License

Oops! 😬

You need to be logged in before you can do that.

Log in with GitHub

Oops! 😬

You need to be logged in before you can do that.

Log in with GitHub

How does the accessibility report work?

When a solution is submitted, we use axe-core to run an automated audit of your code.

This picks out common accessibility issues like not using semantic HTML and not having proper heading hierarchies, among others.

This automated audit is fairly surface level, so we encourage to you review the project and code in more detail with accessibility best practices in mind.

How does the CSS report work?

When a solution is submitted, we use stylelint to run an automated check on the CSS code.

We've added some of our own linting rules based on recommended best practices. These rules are prefixed with frontend-mentor/ which you'll see at the top of each issue in the report.

The report will audit all CSS, SCSS and Less files in your repository.

How does the HTML validation report work?

When a solution is submitted, we use html-validate to run an automated check on the HTML code.

The report picks out common HTML issues such as not using headings within section elements and incorrect nesting of elements, among others.

Note that the report can pick up “invalid” attributes, which some frameworks automatically add to the HTML. These attributes are crucial for how the frameworks function, although they’re technically not valid HTML. As such, some projects can show up with many HTML validation errors, which are benign and are a necessary part of the framework.

How does the JavaScript validation report work?

When a solution is submitted, we use eslint to run an automated check on the JavaScript code.

The report picks out common JavaScript issues such as not using semicolons and using var instead of let or const, among others.

The report will audit all JS and JSX files in your repository. We currently do not support Typescript or other frontend frameworks.

Oops! 😬

You need to be logged in before you can do that.

Log in with GitHub