Understanding Context API with a Use Case

#day9learningReact

Understanding Context API with a Use Case

Photo by Trent Erwin on Unsplash

Introduction:

Consider an example of e-commerce website with a page containing a list of products and their details such as product description, price, add to cart option, etc. Using the context API on click of add to cart button the items must be added to the cart component and the total has to be updated.

To create this functionality let us see the following steps:

  1. Create a component Product. The product details are taken using props.

     export const Product=(name, price)=>{
         return(
         <div>
             <h4>{name}</h4>
             <p>price: ${price}</p>
             <button>add to cart</button>
         </div>
         )};
    
  2. Render this Product component in app.js.

     function App() {
       return (
         <div className="App">
           <Product name="Lenovo" price={100000}/>
           <Product name="Mac book" price={500000}/>
           <Product name="Smart watch" price={1000}/>
         </div>
       );
     }
     export default App;
    
  3. Create another component Cart which shows the list of added items.

     export const Cart =()=>{
         return(
             <div>
                 <li>Lenovo :$1000000</li>
                 <h5>total: $</h5>
             </div>
         )
     }
    
  4. Now create a context along with the context provider and pass the state variable cart item and setItems function as props.

     import { createContext, useState} from "react";
    
     export const CartContext = createContext(null);
    
     export const CartProvider = (props)=>{
         const [items, setItems] =useState([]);
         return(
             <CartContext.Provider value={{items, setItems}}>
                 {props.children}
             </CartContext.Provider>
         );
     }
    
  5. In index.jsx wrap the components in context provider so that the child component within can access the context values.

  6. On click of add to cart let us create functionality to add items into the cart. Import context in both the Product and Cart components file. Call an Onclick function on button and using setItems function add the item to the list.

     <div>
             <h4>{name}</h4>
             <p>price: ${price}</p>
             <button onClick={()=> cart.setItems(...cart.items,{name:name,price:price})}>add to cart</button>
         </div>
    
  7. When add to cart is clicked the items are added to the cart list.

  8. After importing CartContext in Cart component file now check if there are items in the cart and render li for each item in the cart.

     <h1> Cart </h1>
     {
         cart && cart.items.map(item => <li>{item.name}-{item. Price}</li>)
     }
    
  9. Now show the total cost of values in the cart. In Product component create total variable and set initial value as 0.

     const total = cart.items.reduce((a,b) =>a+b.price,0)
    
  10. Display this total value in the <H1> tag of Product Component.3