How To Add Wishlist In Next Js & React js (2024)

How To Add Wishlist In Next Js React js
432 Views
4.2
(692)

Integrating a wishlist into your Next.js and React.js applications enhances user experience by allowing them to save items for future reference. This feature is particularly useful in e-commerce sites, where it can significantly impact user engagement and sales.

In this post, we’ll walk you through the steps to add a Wishlist in React.js, ensuring you have a functional and user-friendly feature by the end.

Introduction

A wishlist allows users to mark items they are interested in but are not ready to purchase. This functionality not only improves the shopping experience but also provides valuable insights into customer preferences.

Implementing a Wishlist in React.js and Next.js requires a blend of frontend and backend skills, but we’ll focus on the frontend aspect, using state management and context API to store our Wishlist data. Now, let’s go to the point:

Steps to Add Wishlist In Next Js & React js

1. Install Library in Reactjs

First, ensure your project setup is ready. If you’re working with Next.js, your React.js environment is inherently set. We’ll use a state management library, such as Redux or Context API, for handling our Wishlist state. For this guide, we’ll stick with Context API for simplicity.

- npm i react

This command installs the necessary library to manage a global state, like a Wishlist, across your React components.

This function takes an item and adds it to the existing wishlist array. Ensure you’ve set up your Context API provider to manage the wishlist state across your application.

2. Create addToWishList function:-

// add To WishList was use add product in WishList
const addToWishList = (data) => {
   // Load wishlist from localStorage
   const storedWishList = localStorage.getItem("wishList");
   const initialWishList = storedWishList ? JSON.parse(storedWishList) : [];


   // Check if the data is already in the wishlist
   if (!initialWishList.find((item) => item.id === data.id)) {
       const updatedWishList = [...initialWishList, data];


       // Update localStorage with the updated wishlist
       localStorage.setItem("wishList", JSON.stringify(updatedWishList));
   }
}

export default addToWishList;

3. Add addToWishList function in add Wishlist button:-

import React, { useEffect, useState } from "react";


const [is_Wishlist, setisWishlist] = useState(true);


 const wish_list_set = () => {
   const storedWishList = localStorage.getItem('wishList');
   const product_data = JSON.parse(storedWishList)
   if (product_data !== null) {
     const isWishlist = product_data.some((item) => item.id === data.id);
     setisWishlist(isWishlist)
   }
 }


 const wish_list_update = (data) => {
   localStorage.setItem("wishList", JSON.stringify(data));
 }




 const handlerAddToWishlist = (e) => {
   e.preventDefault();
   const storedWishList = localStorage.getItem('wishList');
   const isWishlist = JSON.parse(storedWishList).some((item) => item.id === data.id);
   if (isWishlist !== true) {
     addToWishList(data);
     setisWishlist(true)
   } else {
     const storedWishList = localStorage.getItem('wishList');
     const product_data = JSON.parse(storedWishList)
     const updatedWishList = product_data.filter((item) => item.id !== data.id);
     wish_list_update(updatedWishList)
     setisWishlist(false)
   }
   document.getElementById("refresh-wishlist").click();
 };


 useEffect(() => {
   wish_list_set()
 }, []);

// button to add new product
<Link
 href="#"
 onClick={handlerAddToWishlist}
 className={`wishlist-btn${is_Wishlist ? ' add' : ''}`}
>
{ is_Wishlist ? “not heart” : “heart” }
</Link>

4. List to Wishlist:-

import React, { useState, useEffect } from "react";
import Link from "next/link";


// this Component was a Wishlist this was use for add to Wishlist and display Wishlist on Wishlist page
const Wishlist = ({ initialValues_data }) => {
 const [wishList, setWishList] = useState([]);


 const productInCart = (d) => items.some((item) => item.id === d);


 useEffect(() => {
   const storedWishList = localStorage.getItem("wishList");
   if (storedWishList) {
     setWishList(JSON.parse(storedWishList));
   }
   document.getElementById("refresh-wishlist").click();
 }, []);


 useEffect(() => {
   // Update localStorage when the wishlist changes
   localStorage.setItem("wishList", JSON.stringify(wishList));
   document.getElementById("refresh-wishlist").click();
 }, [wishList]);


 const removeItem = (productId) => {
   document.getElementById("refresh-wishlist").click();
   const updatedWishList = wishList.filter((item) => item.id !== productId);
   setWishList(updatedWishList);
   document.getElementById("refresh-wishlist").click();
 };


 const clearWishList = () => {
   document.getElementById("refresh-wishlist").click();
   setWishList([]);
   document.getElementById("refresh-wishlist").click();
 }; };


 if (wishList.length === 0) {
   return (
     <section className="wishlist-grid-section style-3 section-two">
       <div className="container">
         <div className="row">
           <div className="d-flex flex-column justify-content-center align-items-center">
             <img
               src="images/cart-wishlist.svg"
               alt="cart-cart.svg"
               className="mb-3 object-fit-contain"
               style={{ maxWidth: "140px" }}
             />
             <h3 className="mb-3">Your Wishlist is empty</h3>
             <p className="mb-3">
               Seems like you don't have wishes here. Make a wish!
             </p>
             <div className="flex items-center justify-center cart-now-btn">
               <Link
                 name="continue_shopping"
                 className="btn btn-dark"
                 href="/shop"
               >
                 Continue Shopping
               </Link>
             </div>
           </div>
         </div>
       </div>
     </section>
   );
 }

<Link href="" className="remove-link" onClick={clearWishList}>
Remove all <span className="ti-trash"></span>
</Link>


<Link href="" className="product-close-icon">
   <span className="ti-close" onClick={() => removeItem(d.id)} ></span>
</Link>

5. removeItem function used to remove one item from WishList:-

- removeItem(id)

6. clearWishList function used to remove all items from WishList :

- clearWishList

7. Show the count of products in the wishlist in the header wishlist icon:-

import React, { useEffect, useState } from "react";


const [is_Wishlist, setisWishlist] = useState(false);


const wish_list_set = () => {
const storedWishList = localStorage.getItem('wishList');
if (storedWishList) {
const product_data = JSON.parse(storedWishList)
   if (product_data !== null) {
       setisWishlist(product_data.length)
     }
} else {
   setisWishlist(0)
  }
}


const refresh_wishlist = () => {
  wish_list_set()
}


useEffect(() => {
  wish_list_set()
}, []);


<span className='d-none' id="refresh-wishlist" onClick={refresh_wishlist}></span>


<div className="header-button">
   <Link href="/wishlist" className="wishlist-icon">
     <img src="images/wishlist-icon.svg" alt="wishlist icon" />
        <span className="count">{is_Wishlist}</span>
   </Link>
</div>

Conclusion

Implementing a wishlist feature in your Next.js and React.js applications involves setting up a global state for the wishlist, creating functions to add and remove items, and updating the UI to interact with these functions.

By following the steps outlined in this guide, you’ll enhance your application’s functionality and user experience, making it easier for users to save and manage their favorite items. Remember, a well-implemented wishlist can significantly contribute to the usability and appeal of your e-commerce site or application.

By mastering these techniques, you’re not just adding a new feature to your application; you’re also deepening your understanding of state management in React.js and improving your ability to create dynamic and interactive web applications.

How useful was this blog?

Click on a star to rate it!

Average rating 4.2 / 5. Vote count: 692

No votes so far! Be the first to rate this blog.

Leave a comment

Your email address will not be published. Required fields are marked *