[SOLVED] if i click button then show this button id in reactJs

Issue

i create a onclick function const showContent=(id)=>{} and if i click the perticular button they will show id in const showContent = (id)=>{console.log(id)} like this …..

inside thisCart.jsx i rendering CartStyle.jsx using map method so this delete button inside here.

Cart

function Cart() {
  const [data, setData] = useState([])
  useEffect(() => {
    const data = JSON.parse(localStorage.getItem('Cart'));
    data.map(async (v) => {
      try {
        axios.get(`/cart/${v}`)
          .then((res) => {
            return setData((preV) => {
              return [...preV, res.data]
            })
          })
          .catch(e => { console.log(e) })
      } catch (e) {
        console.log(e);
      }
    })
  }, [])
  
  const showContent=(id)=>{
    console.log('this is id', id)
  }
  return (
    <>
      <div className=" cartStyle row g-3">
        <div className="left col-md-4">         
            <button className="btn btn-primary">Proceed to Buy</button>
          </div>
        </div>
        <div className="right col-md-8 flex flex-wrap justify-around">

          {
            data.map((v, i) => {
              return <CartStyle
                key={i}
                id={i}
                title={v.title}
                price={v.DiscountPrice}
                img={v.image}
                delete={showContent(i)}
              />
            })

          }
        </div>
      </div>
    </>
  )
}


export { Profile, Cart };

CartStyle
this is a CartStyle means i’m passing data from Cart.jsx to CarStyle.jsx using props

const CartStyle= (props) => {
return (
  <>
    <div style={{ width: '22em', height: '10em'}} className=" p-2 row g-3 card container rounded-2xl shadow py-2 my-3">
        <button id="delBtn" onClick={props.delete} className="btn btn-primary my-2">Delete</button>
      </div>
    </div>
  </>
)
};

export default CartStyle;

Solution

<CartStyle
  key={i}
  id={i}
  title={v.title}
  price={v.DiscountPrice}
  img={v.image}
  delete={(i) => showContent(i)} // or delete={showContent}
/>
// CartStyle
<button id="delBtn" onClick={() => props.delete(props.id)} className="btn btn-primary my-2">Delete</button>

Answered By – ldruskis

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.