Beginner’s Guide to Creating a Shopping Cart in React JS

Posted by


In this tutorial, I will guide you through creating a simple shopping cart in React JS for beginners. We will be using React hooks to manage state and functional components to build our cart.

Step 1: Setting up the environment
Before we start building our shopping cart, make sure you have Node.js installed on your machine. If not, you can download and install it from the official website.

Next, create a new React project using Create React App. Open your terminal and run the following command:

npx create-react-app shopping-cart

Once the project is created, navigate to the project directory by running:

cd shopping-cart

Now, start the development server by running:

npm start

Step 2: Creating the Cart Component
Inside the src folder, create a new folder called components. Inside this folder, create a new file called Cart.js. This will be our main component for the cart.

In the Cart.js file, start by importing React and defining a functional component called Cart:

import React from 'react';

function Cart() {
  return (
    <div>
      <h2>Shopping Cart</h2>
    </div>
  );
}

export default Cart;

Step 3: Adding Products to the Cart
Next, let’s create a list of products that the user can add to the shopping cart. Inside the components folder, create a new file called Products.js:

import React from 'react';

const products = [
  { id: 1, name: 'Product 1', price: 10 },
  { id: 2, name: 'Product 2', price: 20 },
  { id: 3, name: 'Product 3', price: 30 },
];

function Products() {
  return (
    <div>
      <h2>Products</h2>
      <ul>
        { products.map(product => (
          <li key={product.id}>
            {product.name} - ${product.price}
            <button>Add to Cart</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default Products;

Step 4: Managing State with Hooks
Now let’s add state management to our app using React hooks. Inside the src folder, create a new file called App.js:

import React, { useState } from 'react';
import Cart from './components/Cart';
import Products from './components/Products';

function App() {
  const [cart, setCart] = useState([]);

  const addToCart = (product) => {
    setCart([...cart, product]);
  }

  return (
    <div>
      <Cart cart={cart} />
      <Products addToCart={addToCart} />
    </div>
  );
}

export default App;

Step 5: Updating the Cart Component
Finally, let’s update the Cart component to display the items added to the shopping cart:

import React from 'react';

function Cart({ cart }) {
  return (
    <div>
      <h2>Shopping Cart</h2>
      <ul>
        { cart.map(item => (
          <li key={item.id}>
            {item.name} - ${item.price}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default Cart;

Step 6: Styling with CSS
To make your shopping cart look more presentable, you can add some CSS styles. Create a new file called App.css inside the src folder and add the following styles:

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 960px;
  margin: 0 auto;
  padding: 20px;
}

h2 {
  margin-bottom: 10px;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  margin-bottom: 10px;
}

And then import the CSS file in the App.js file:

import './App.css';

That’s it! You have now successfully created a simple shopping cart in React JS. You can further enhance this app by adding features like removing items from the cart, calculating the total price, and more. Happy coding!

0 0 votes
Article Rating

Leave a Reply

39 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@hardwired66
2 hours ago

Useeffect everywhere my Lord? 😮

@Huy-G-Le
2 hours ago

Thank you, but it's took me 2.5 days to finish this project.

@freudian.
2 hours ago

how to make totalPrice sir?

@tewodrosii1084
2 hours ago

best, THANK U!!

@staff6543
2 hours ago

Why are you shouting? Please try to speak more fluently and calmly. It was an irritating training. The video may be educational but the presentation is terrible.

@afifarfan244
2 hours ago

How can I get the images?

@alijonovdoniyor9691
2 hours ago

Hi! I have another idea. Back in the day, Material Design had a neat animated hamburger icon on the app bar that rotated as you dragged the drawer. The cool part was that the rotation percentage of the icon matched how much the drawer was pulled from the side towards the center, allowing you to play with the animation while dragging. It was a really nice effect. Could you recreate that using just CSS or CSS with a bit of JavaScript?

@motivatedmomin
2 hours ago

Brilliant professional developer

@rabbitcafe
2 hours ago

How to change fake data to fetch api in products.js ?

@ApnaCodingSchoolOfficial
2 hours ago

Ai voice ?

@jimmya3430
2 hours ago

Provider thing on 13:26 is not working for me

@srk07
2 hours ago

am newbie i can only understand 70% of it so i think this is not for newbie but super usefull

@nazrinrustamova6239
2 hours ago

thank youu!!! this was soo interesting and understandable

@anuvette
2 hours ago

how to animate that card going inside the shopping cart and disappearing? can someone help me

@sophiachristygj
2 hours ago

Thank you, Lun! ❤

@PriyanshuSoni-n2c
2 hours ago

Thanks bro love from India ❤

@goatreaper4363
2 hours ago

Is this possible on dreamweaver

@xendo2d987
2 hours ago

what is your vs code theme?

@Funj1co
2 hours ago

I really like the when Mr Beast teachs react😁😅

@abdalrhmanabdalrhman5278
2 hours ago

is that MRBEAST ???

39
0
Would love your thoughts, please comment.x
()
x