Home > Back-end >  Send data or state to another React Page
Send data or state to another React Page

Time:10-18

So, I have a troubles with my react project.

I need to send some data (or also it can be state (true or false)) to the another page. Im using the react-router-dom.

import { useState } from "react"
import ProductToCart from "./ProductToCart"
import Cart from "../../Pages/Cart"

const Buy = () => {
  const [buttonText, setButtonText] = useState("Add to cart")
  const [isActive, setIsActive] = useState(false)
  const addToCart = () => {
    setIsActive((current) => !current)
    setButtonText("Added to the cart ✓")
    if (isActive) {
      setButtonText("Add to cart")
    }
  }
  return (
    <div>
      <button
        class='buy'
        style={{
          fontSize: isActive ? "0.8rem" : "1rem",
          color: isActive ? "lightgray" : "white",
        }}
        onClick={() => {
          addToCart()
        }}
      >
        {buttonText}
      </button>
    </div>
  )
}

export default Buy

After button is pressed/unpressed, I need to send this to the page Cart.js, where I wanna show product in the cart. And do something like:

if (value from Buy.js is true) {
do something 
}

I already tried <Link> but I dont need redirect to Cart.js, I only need to send a value. May be I do something wrong, but if you can tell me just how to send data between the pages without redirect it will be fine... thank you!

CodePudding user response:

The cart state should likely be global, or otherwise accessible from multiple components.

Because even if you're not on the "buy" page, you will need other pages to be able to navigate to the cart, or view the "count" of items in the cart.

Sounds like you need a state management library!

I'd recommend recoil for this use-case, its very lightweight (unlike other popular options like redux).

https://recoiljs.org/

Simply set up a cart atom and append products when the user clicks "buy" then you can use this state in the cart.

CodePudding user response:

Here, You just have to make the state in parent components a global state and pass the state value to the cart component as props.

import React, { useState } from "react";
import Item from "./cart.js";

const Home = () => {
  const [products, addproduct] = useState([]);

  const addToBasket = () => {
    addproduct();// add product here 
  };

  return (
    <div className="container">
      <Cart product={products}/> 
    </div>
  );
};
  • Related