Add To Cart Functionality Using React.js
Published: 2023-03-22 04:09:52

Software engineering bootcamp that will change my life? Yes please, add to cart!  Here is the simplest way I can show you how to add to cart using React JS.

First you must create the seed data in your backend in your seeds.rb file if you are using Ruby on Rails backend.  Add a boolean attribute for the product in your backend Ruby on Rails program and set the boolean to false. 

```
Shoe.create!(
    shoe_name: "Jordan 2",
    in_cart: false
)
```

Then you must make a fetch/get request in your App.js folder to your backend to receive the shoe data to display it.
First you must add a constant to the function App() and then add the get/fetch request and pass it down to the return function.

```
    function App () {
        const [shoes, setShoes] = useState([])

        useEffect(() => {
        fetch("/shoes")
        .then((r)=>r.json())
        .then(shoes=>{setShoes(shoes)})
        }, [])

        return (
            <div>
                <ShoeList
                    shoes={shoes}
                >
            </div>
        )
    }
```

In order to get the seed data to actually render on the web application you must pass down the shoe as a prop down to the ShoeList.js file.  You then should create a const and continue passing the props down.

```
function ShoeList({shoes}) {
        const shoeList = shoes.map((shoe) => (
            <ShoeCard
                key={shoe.id}
                shoe={shoe}>
        ))

    return(
        <div>{shoeList}</div>
    )
}
```

Then go to your ShoeCard.js component and pass down the shoe as a prop to the function ShoeCard. You need to also create a const for the shoe in order for the attributes to render.

```
function ShoeCard ({shoe}) {
    const{id, name, image, price, retailPrice, releaseYear, colorway, cart}=shoe;

    return (
        <div>
            <img src={image} alt={name}/>
            <p><b>Price:</b>{price}</p>
            <h4>{name}</h4>
            <p><b>Retail Price:</b>{retailPrice}</p>
            <p><b>Release Year: </b>{releaseYear}</p>
            <p><b>Colorway:</b>{colorway}</p>
        </div>
    )
}
```

After you get your seed data to render you must go back to your upper most component where we created a fetch request from which would be the App.js file.  In here you will create two functions that will handle the add to cart and handle remove from cart functionality.

```
function App () {
    const [shoes, setShoes] = useState([])

    useEffect(() => {
        fetch("/shoes")
        .then((r)=>r.json())
        .then(shoes=>{setShoes(shoes)})
    }, [])

    function handleAddToCart(addShoeToCart) {
        const inCart=shoes.map((shoe) => {
            if(shoe.id === addShoeToCart.id) {
                return addShoeToCart;
            } else {
                return shoe;
            }
        })
        setShoes(inCart);
    }

    function handleRemoveFromCart(removeFromCart) {
        const removeShoe = shoes.filter((shoe) => 
        shoe.id !==removeFromCart.id);
        setShoes(removeShoe)
    }


    return (
        <div>
            <ShoeList
                shoes={shoes}
                onAddToCart={handleAddToCart}
                onRemoveFromCart={handleRemoveFromCart}
            />
        </div>
        )
}
```

Then go back to the ShoeList.js component and pass down the onAddToCart and onRemoveFromCart as props.

```
function ShoeList({shoes, onAddToCart, onRemoveFromCart}) {
    const shoeList = shoes.map((shoe) => (
        <ShoeCard
            key={shoe.id}
            shoe={shoe}
            onAddToCart={onAddToCart}
            onRemoveFromCart={onRemoveFromCart}
        />
    ))

    return(
        <div>{shoeList}</div>
    )
}
```

Finally go to your lowest component which is the ShoeCard.js.  Here we must continue to pass down the onAddToCart and onRemoveFromCart functions.   We will then create a const  to set the state of the shoe inCart.  To use this state we will create a handleCartChange Patch request.  Then you must create an inCart button ternary in the return function.

```
function ShoeCard ({shoe, onAddToCart, onRemoveFromCart}) {
    const {id,name,image,price,retailPrice,releaseYear,colorway,cart}=shoe;
    const [inCart,setInCart]=useState(cart)

    function handleCartChange() {
        setInCart((inCart)=>!inCart);
            fetch (`http://localhost:3000/shoes/${id}`, {
                method:"PATCH",
                headers:{
                    "Content-Type":"application/json",
                },
                body:JSON.stringify({cart:!cart})
            })
            .then((r)=>r.json())
            .then((addedToCart)=>setInCart ?onAddToCart(addedToCart):onRemoveFromCart(addedToCart))
    }

    return (
        <div>
            <img src={image} alt={name}/>
            <p><b>Price:</b>{price}</p>
            <h4>{name}</h4>
            <p><b>Retail Price:</b>{retailPrice}</p>
            <p><b>Release Year: </b>{releaseYear}</p>
            <p><b>Colorway:</b>{colorway}</p>

            {inCart?(
                <button onClick={handleCartChange}>Remove From Cart</button>
            ):( <button onClick={handleCartChange}>Add To Cart</button>)}
            </div>
        );
}
```