简体   繁体   中英

How can I use the hook's value from one jsx to other

I am making a cart and when we click Add to cart then the number increases this is done using hooks and is in the following Pricetag.jsx

import React from 'react'
import './Body.css'
import { useState } from 'react'
// import './Cart.js'
export default function Pricetag(props) {
  const [count, setCartCount] = useState(0);
  return (
    <div>
      <div className="card1">

        <div className="image">
          <img src={props.images} alt="" className='card-image' />
        </div>

        <div className="content">

          <div className="name">
            {props.name}
          </div>

        </div>

        <div className="button">
          <button className='btn no1' id='cartbutton' onClick={() => setCartCount(count + 1)} >
            Add to cart 
          </button>
          <br></br>
        </div>
      </div>

    </div>
  )
}

Now I want to use the value of count in other jsx

import React from 'react'
import './Body.css'
import image2 from './assets/cake9.jpeg'
import image9 from './assets/cake16.jpeg'
import Pricetag from './Pricetag'
export default function Body(props) {
  return (
    <>
      <div className="headingbody">
        <div></div>
        {props.title}
      </div>
      <div className="cart">
              <div className="number34">  ** here I want to show my count **</div>
              <i class="fa-solid fa-cart-shopping"></i>
      </div>
        <hr className='latestline' />
      <div className='container1'>

        <Pricetag images={image10} name="Swimming cake" bold="Rs 345" cut="Rs 634" />
        <Pricetag images={image11} name="Rossy cake" bold="Rs 345" cut="Rs 634" />
      </div>

    </>
  )
}

Can you tell me how can I use the value of count from the first to second?

There are a few ways you can use:

  • state management: redux, zustand,...
  • using React Context
  • you can pass the value through props but it will cause 'hell props'

You have to pass the count state to the other JSX file (component). There are some ways:

  1. Import the JSX file and call the component inside Pricetag.jsx, then pass count as a prop.
  2. If you are unable to use the component inside Pricetag.jsx, then Use state management solutions like Context API, Redux, MobX etc.

brother, you can find the description and idea from the below document of useContext API calling and its functionaloty

https://www.geeksforgeeks.org/reactjs-usecontext-hook/

https://reactjs.org/docs/hooks-reference.html#usecontext

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM