Build Simple Ecommerce site using React and Jotai

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Retail Ecommerce website can be created quickly with React. It can be created using React, Bootstrap, React DOM and Jotai. Data flow within the commerce site is done using Jotai in a light-weight manner. The main workflow of showing all the items in the gallery to user and user adding to the cart will be done as part of this blog.

react and react-dom packages are used to create the ecommerce website UI screens. To create a responsive UI, bootstrap is used. The data or the model flow of the application can be managed in a lightweight manner by jotai. 

We assume that you have some familiarity with React, Boostrap and SASS. Please follow the links to learn basics of React and Bootstrap.   

Jotai Introduction:

Jotai is primitive and flexible state management for react. It is a minimalistic API to store the state in atoms and easily wired to components at any level of DOM hierarchy. It is as simple to use as React’s integrated useState hook, but all state is globally accessible, derived state is easy to implement, and extra re-renders are automatically eliminated.

Setup the project:

Create the sample react application using the below command. It will create a basic react project with required react package dependencies. Public folder will have the index.html having the div element with root id. 

npx create-react-app my-app

App Component: 

React starts from the App component which is the root component of the application. It contains the Home component which is the home page of the web application. Home component is enclosed with the Provider which is from Jotai. Jotai is the global state management provider which is available for any child components of the Home component (src/App.js). 

function App() {
  return (
    <Provider>
      <div className="App">
        <Home />
      </div>
    </Provider>
  );
}


Home Component: 

Home component has the navbar which has the title of the site and cart icon on the right. Products component lists the product items in the home page. Cart display component will show all the items present in the cart. If there are no items in the cart, it will disable the proceed to checkout items (src/Home.js). 

export default function Home() {
  const [cart, setCart] = useAtom(cartAtom);
  const forceUpdate = React.useState()[1].bind(null, {});
  return (
    <div>
      <>
        <Navbar bg="light" expand={false} fixed="top">
          <Container fluid>
            <Navbar.Brand></Navbar.Brand>
            <Navbar.Brand className="headerText">Shopping Cart Example</Navbar.Brand>
            <Navbar.Offcanvas 
                                 id="offcanvasNavbar" 
                                 aria-labelledby="offcanvasNavbarLabel" 
                                 placement="end">
              <Offcanvas.Header closeButton>
                <Offcanvas.Title id="offcanvasNavbarLabel">Your Cart</Offcanvas.Title>
              </Offcanvas.Header>
              <Offcanvas.Body>
                <>
                  <div>
                  <CartDisplay/>
                    <div className="action-block">
                      <button
                        type="button"
                        className={{ disabled: cart && cart.length === 0 }}
                        onClick={() => {
                          setCart([]);
                          forceUpdate();
                        }}
                      >
                        PROCEED TO CHECKOUT
                      </button>
                    </div>
                  </div>
                </>
              </Offcanvas.Body>
            </Navbar.Offcanvas>
            <Navbar.Toggle aria-controls="offcanvasNavbar">
              <img src={Cart} alt="" height={30} width={30} />
            </Navbar.Toggle>
          </Container>
        </Navbar>
        <Products />
      </>
    </div>
  );
}

Products Component:

Products component will get the products from products json file and then iterate to create card for each product item. 

export function Products() {
  return (
    <div>
      <>
        <div className="">
          <div className="products">
            {productsJson.map((data) => {
              return <ProductCard key={data.id} data={data} />;
            })}
          </div>
        </div>
      </>
    </div>
  );
}

products classnames which make a flex display dom element where all the product items are displayed. It will be responsive so that it will display the items with equal spacing and common width across the items (src/assets/scss/components/_products.scss). 

.products {
  display: flex;
  display: -webkit-flex;
  flex-wrap: wrap;
  -webkit-flex-wrap: wrap;
  padding: 16px;
  max-width: 960px;
  margin: 40px auto;
  @media (max-width: 768px) {
    padding: 8px;
  }
  .product {
    min-height: 355px;
    flex-basis: calc(25% - 32px);
    -webkit-flex-basis: calc(25% - 32px);
    @media (max-width: 768px) {
      flex-basis: calc(33% - 16px);
      -webkit-flex-basis: calc(33% - 16px);
      margin: 8px;
    }
    @media (max-width: 480px) {
      flex-basis: calc(50% - 16px);
      -webkit-flex-basis: calc(50% - 16px);
      min-height: 313px;
      .product-name {
        height: 20px;
        overflow: hidden;
      }
      .product-action {
        padding: 16px 8px;
      }
    }
    @media (max-width: 320px) {
      flex-basis: 100%;
      -webkit-flex-basis: 100%;
    }
  }
}

ProductCard component: 

Product card will display the product image followed by the price and option for selecting the quantity. Action button to add the selected item with the quantity to the cart. Once added, it will show added for a few seconds for the user confirmation using the isAdded state variable. Internally items and quantity will be added to the cart atom so that the cart component knows about the item getting added (src/ProductCard.jsx).  

const ProductCard = ({ data }) => {
  const [isAdded, setIsAdded] = useState(false);
  const [value, setValue] = useState(1);
  const [cart, setCart] = useAtom(cartAtom);
  const {image, name, price } = data;

  const handleAddToCart = () => {
    const product = { ...data, quantity: value };
    const d = [...cart, product];
    setCart(d);
    setIsAdded(true);
    setTimeout(() => {
      setIsAdded(false);
    }, 3500);
  };

  return (
    <div className="product">
      <div className="product-image">
        <img src={image} alt={name} />
      </div>
      <h4 className="product-name">{name}</h4>
      <p className="product-price">{price}</p>
      <div className="stepper-input">
        <p
          className="decrement"
          onClick={() => {
            if (value > 1) {
              setValue(value - 1);
            }
          }}
        >
          –
        </p>
        <input
          type="number"
          className="quantity"
          name="quantity"
          min="1"
          defaultValue="1"
          value={value}
          onChange={(e) => {
            setValue(e.target.value);
          }}
        />
        <p
          className="increment"
          onClick={() => {
            setValue(value + 1);
          }}
        >
          +
        </p>
      </div>
      <div className="product-action">
        <button className={!isAdded ? "" : "added"} type="button" onClick={handleAddToCart} disabled={isAdded}>
          {!isAdded ? "ADD TO CART" : " ADDED"}
        </button>
      </div>
    </div>
  );
};

CartDisplay Component: 

CartDisplay iterates the cart atom to show the items with the selected quantity. Product price and quantity calculated as the amount and displayed against each product item. Product remove button will remove the item by nullying the item in the cart state item which internally updates the cart atom (src/CartDisplay.jsx). 

const CartDisplay = ({ data }) => {
    const [cart, setCart] = useAtom(cartAtom);
    const forceUpdate = React.useState()[1].bind(null, {});

    return ( <ul className="cart-items">
    {cart.map((product) => {
      // console.log("product", product);
      return (
        <li className="cart-item" key={product.name}>
          <img className="product-image" src={product.image} alt="" />
          <div className="product-info">
            <p className="product-name">{product.name}</p>
            <p className="product-price">{product.price}</p>
          </div>
          <div className="product-total">
            <p className="quantity">
              {`${product.quantity} ${product.quantity > 1 ? "Nos." : "No."}`}
            </p>
            <p className="amount">{product.quantity * product.price}</p>
          </div>
          <button
            className="product-remove"
            onClick={() => {
              const index = cart.findIndex((pro) => pro.id === product.id);
              cart.splice(index, 1);
              setCart(cart);
              forceUpdate();
            }}
          >
            ×
          </button>
        </li>
      );
    })}
  </ul>);
}

Complete flow of the adding the item to product and showing it in cart is shown in below image. 

Github reference: https://github.com/devgroves/shoppingcartbyjotai

 


   

DevGroves Technologies is a IT consulting and services start-up company which is predominately to web technologies catering to static website, workflow based CRM websites, e-commerce websites and reporting websites tailoring to the customer needs. We also support open source community by writing blogs about how, why and where it need to be used for.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

React Reduce Vs Jotai

  • jottai react redux

While developing web applications, we built many components and having a data model across the application wide model will be difficult. We need common store management to update and get information across all the components. In React based Web UI, redux is the official centralized state management to be used which is internally wired as state changes to the component. There are other alternatives to redux which are light-weight and simple to use. One among them is Jotai, a minimalistic API for state management. In this blog we will take one of the redux examples given in the redux site and do the same in Jotai for deeper understanding.

Read More


Laravel eCommerce Platform - Bagisto

  • ecommerce shopping laravel php

Nowadays on the web, Shopping is one of the most popular activities. Everyone can shop at their recess, anytime from anywhere. However, this is interesting that anyone can have their pages built to display their favourite products and services.

Read More


5 Tips On Project Management for Ecommerce Businesses

  • ecommerce e-commerce project-management

Running an ecommerce business is tricky. There is a lack of location which means that your opportunities are bigger but there is also a lot of pressure. Ecommerce business and website is a project on its own and it’s always changing. It’s also a source of numerous other projects. So, project management is one of the most important aspects of it.

Read More


AbanteCart - Easy to use open source e-commerce platform, helps selling online

  • e-commerce ecommerce cart php

AbanteCart is a free, open source shopping cart that was built by developers with a passion for free and accessible software. Founded in 2010 (launched in 2011), the platform is coded in PHP and supports MySQL. AbanteCart’s easy to use admin and basic layout management tool make this open source solution both easy to use and customizable, depending on the skills of the user. AbanteCart is very user-friendly, it is entirely possible for a user with little to no coding experience to set up and use this cart. If the user would be limited to the themes and features available in base AbanteCart, there is a marketplace where third-party extensions or plugins come to the rescue.

Read More


Build Consulting Website using Next.js

  • react nextjs website-development ssr

One of the popular web framework for building Single page application (SPA) or static site is React library. Application built with React packages will be rendered completely on the client side browser. If you want to reduce the load on client side browser, we need to pre-render the pages in server (Serer side rendering) and serve it to the client. So the client loads the page like simple html page. Also if the pages are rendered from server then search engine will be able to fetch and extract the pages. To do SSR for React, the best abstraction framework is Next.js. In this blog, we will explain how to build a simple consulting website using NextJS.

Read More



Blockchain Technology Will Revolutionize These Five Industries

  • blockchain security industries

Blockchain is buzzing across the world with its endless potential for disrupting a broad spectrum of the industries beyond the storage and transferring the values. Cryptocurrencies are revolutionizing variant industries and plenty of people talk about it with and their potential. Blockchain technology may have been made for bitcoins but it has immense potential for making the transactions secure and exciting. The technology is not ubiquitous but it already seems to be disrupting a huge number of the highly centralized industries that demonstrate practical use cases for changing the way businesses are done.

Read More


SeoToaster: easy, fast and efficient open source CMS for top SEO performance

  • cms content-management-system seo ecommerce

SeoToaster is a free Open Source CMS & Ecommerce solution to build, manage and market websites optimized for for top search engine performance. As the name implies, Seo Toaster is to date the only content management system (CMS) to truly integrate SEO execution and web marketing automation technology in full compliance with the search engines industry’s best practices.

Read More


PrestaShop - A feature rich Open Source eCommerce solution

PrestaShop is an Open Source eCommerce Solution. It comes complete with over 310 features that have been carefully developed to assist business owners in increasing sales with virtually little effort. It is being used in more than 150,000 online stores.

Read More


Data Fetching and Form Building using NextJS

  • nextjs data-fetching form-handling

Next.js is one of the easy-to-learn frameworks for server-side pre-render pages for client-side web applications. In this blog, we will see how we can fetch data from API and make it pre-render pages. Also, let's see how forms work in Next.js and collect the data without maintaining the database.

Read More


React Media Lightbox

  • lightbox gallery react audio video

Lightbox is a popular and widely used concept for showing the gallery of media files. It is a very impressive approach for the end user to glance through media files. Media files like audio or video will load the html audio or video controls.

Read More


Microweber CMS - An open source CMS with Ecommerce support

  • cms e-commerce microweber

To the user's satisfaction, there is a whole wide world of different CMS, all suitable for different needs. You can go for the giants like Wordpress or Joomla or pick one of the rising forces - Shopify, Squarespace or others. Microweber CMS fills a hole in the current technological ecosystem, aimed at delivering a light software that is perfect for all end-users lacking the technical knowledge needed for complicated website building.

Read More


React Patent Clause Licensing issue. Is it something to worry?

  • react react-license facebook

React libraries from Facebook is one of the most used UI libraries. It is competitive to AngularJS. There are many open source UI components or frameworks available but mostly people narrow down to two choices Angular / React. Recently Facebook has updated React license and added a patent clause which makes companies to worry and rethink whether to use React or not.

Read More


Quick Start Programming Guide for redis using java client Jedis

  • redis jedis redis-client programming database java

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This article explains about how to communicate with Redis using Java client Jedis.

Read More


React Window - Optimized way to display large list

  • react react-window large-list

In Web development, there will be always a need to display content in a large list. Rendering a large list will slow down the web page load and increase the First Contentful Paint(FCP). Usually large lists are displayed in a paginated grid where user has to move around pages by clicking next. It will be good user experience, if the same page provides data of large list as and when we scroll.

Read More


React JS Developer Salary Overview

  • reactjs javascript salary

These days, web development is a need for any business - it attracts huge investments and can kick-start businesses. As for the tools mainly used for development, JavaScript is riding the wave right now. StackOverflow has been naming it the most popular programming language for six years straight. React, as one of the most popular JS libraries is also the first choice for interface developers. It offers some of the best web development tools for mobile and single-page applications.

Read More


React Media LightBox - Part 2

  • react lightbox gallery media

In this blog, we will bring the essential features zoom control, download, fullscreen to enhance the view experience of the media items. Lightbox components provide options for captioning the media items as well. Brought all the features only with material design and there are no dependencies required for the functionalities of the media lightbox.

Read More


Scene.js - Library to Create Timeline-Based Animation

  • scenejs css timeline javascript animation motion

Scene.js is a JavaScript timeline-based animation library for creating animation websites. As an animated timeline library, it allows you to create a chronological order of movements and positions of objects.

Read More


Glific - Open Source Two Way Communication Platform for Social Sector Organizations

  • glific elixir communication architecture social-sector

Glific is an open source two way communication platform with primary focus on helping social sector organizations to interact with millions of beneficiaries concurrently through automated messages with rich media content and manual intervention wherever required. With Glific one can design flows to automate conversations, see how each of the beneficiaries is interacting with the bot and measure engagement.

Read More


JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More


Generate PDF from Javascript using jsPDF

  • pdf jspdf javascript

We show lot of data in our web applications, it will be awesome if we quickly download specific part of PDF rather than printing it. It will be easy to share for different stakeholders and also for focused meetings. In web application development, download to PDF means, we need to develop backend api specifically and then link it in frontend which takes longer development cylce. Instead it would be really great, if there is way to download what we see in the user interface quickly with few lines of Javascript, similar to export options in word processing application.

Read More







We have large collection of open source products. Follow the tags from Tag Cloud >>


Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.