skip to Main Content

Im new to React and trying to reuse a cart Button which I made for store, in Navbar and update it.
here is my Store component.
I tried to import All the involving components in Navbar as well and still no luck.
I tried as well useContext() and props but nothing worked. Im very confused right now

Appreciate any help.

import React, { useState, useContext } from "react";
import TrackVisibility from "react-on-screen";
import { Row, Col, Button, Navbar, Modal } from "react-bootstrap";
import { productsArray } from "./productsStore";
import ProductCard from "./ProductCard";
import { CartContext } from "./CartContext";
import CartProduct from "./CartProduct";
import "./Store.css";



const Book = () => {
  const [show, setShow] = useState(false);
  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);
  const cart = useContext(CartContext);

{/*  const checkout = async () => {
    await fetch("http://localhost:4000/checkout", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ items: cart.items }),
    })
      .then((response) => {
        return response.json();
      })
      .then((response) => {
        if (response.url) {
          window.location.assign(response.url); // Forwarding user to Stripe
        }
      });
  }; 
*/}

  const productCount = cart.items.reduce(
    (sum, product) => sum + product.quantity,
    0
  );

  return ( 
   
    <>
      <div
        className="app__store app__bg section__padding flex__center"
        id="booking"
      >
        <Navbar expand="sm" className="app__bg" variant="dark">
          <Navbar.Brand href="/book" className="headtext__cormorant">
           Book a Session{" "}
            <p className="p__opensans"></p>
          </Navbar.Brand>

####   This is the button im trying to reuse in Navbar  ###


          <Button
            className="custom__button"
            variant="success"
            onClick={handleShow}
          >
            Cart ({productCount} Items)
          </Button>


        </Navbar>
        <Modal show={show} onHide={handleClose}>
          <Modal.Header>
            <Modal.Title>Your Booking</Modal.Title>

          </Modal.Header>
          <Modal.Body>
            {productCount > 0 ? (
              <>
                <p>Items in your cart:</p>
                {cart.items.map((currentProduct, idx) => (
                  <CartProduct
                    key={idx}
                    id={currentProduct.id}
                    quantity={currentProduct.quantity}
                  >
                    {" "}
                  </CartProduct>
                ))}
                <h1>Total: {cart.getTotalCost().toFixed(2)}</h1>
                <button className="custom__button" onClick={()=> window.open("https://form.jotform.com/231252553810347")}>
                  Complete Your Order!
                </button>
              </>
            ) : (
              <h1>There are no itmes in your cart!</h1>
            )}
          </Modal.Body>
        </Modal>
      </div>
      <div className="app__bg app__wrapper section__padding">
        <Row xs={1} md={2} lg={4} className="g-4">
          {productsArray.map((product, idx) => (
            <Col align="center" key={idx}>
              <TrackVisibility partialVisibility>
                {({ isVisible }) => (
                  <div
                    className={
                      isVisible ? "animate__animated animate__flipInY" : ""
                    }
                  >
                    <ProductCard product={product} />
                  </div>
                )}
              </TrackVisibility>
            </Col>
          ))}
        </Row>
      </div>
    </>

  );
};

export default Book;

2

Answers


  1. Chosen as BEST ANSWER

    so I found the issue! It was the CartProvider which wasnt including Navbar component and because of that the Button wasnt updating ! I wrapped the Navbar in CartProvider and now it works!

    <CartProvider>
        <Navbar />
        <Header />
        <AboutUs />
        <Massage />
        <Yoga />
        <Energy />
        <Event />
        <Fire />
        <Music />
        <Intro />
          <Container>
            {/* <BrowserRouter>
              <Routes>
                <Route path="success" element={<Success />} />
                <Route path="cancel" element={<Cancel />} />
              </Routes>
            </BrowserRouter> */}
          </Container>
          <Store></Store>
        </CartProvider>
        <Footer />
        </>
    

  2. import { Button } from "react-bootstrap";
    
    const ButtonComponentName = ({ text, onClick, className, variant }) => (
      <Button className={className} variant={variant} onClick={onClick}>
        {text}
      </Button>
    );
    
    export default ButtonComponentName;
    

    It must be something like this.
    With this implementation, the button can be used not only in the navigation component.

    Also note that there is no button type (in bootstrap the default type is ‘button’)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search