Click here to Skip to main content
15,916,180 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I use a map function to list products. There is a Details button in that div. There are 30 products in the JSON file. The products are listed properly.
But if I click the Details button in the window showed only the last 30th id of the products.

What I want:
When I click the n-th product shows the n-th id in the details id="window".

GitHub - folza1/react-modulzaro[^]

Could you solve this?

What I have tried:

JavaScript
import "./App.css";
import cart from "./cart.jpg";
import { useState } from "react";

var data = require("./data.json");

function App() {
  const [isShown, setIsShown] = useState(false);

  const handleClick = (event) => {
    setIsShown(true);
  };

  const handleClickClose = (event) => {
    setIsShown(false);
  };

  return (
    <>
      <h1>Termékek</h1>
      <div id="main">
        {data.map((obj) => (
          <div className="divStyle" key={obj.id}>
            <div
              id="thumbNail"
              style={{ backgroundImage: `url(${obj.thumbnail})` }}
            ></div>
            <div id="product">
              <div id="title">
                <p>{obj.title}</p>
              </div>
              <div id="price">
                <p>${obj.price}</p>
              </div>
              <div
                id="cart"
                style={{
                  backgroundImage: `url(${cart})`,
                }}
              ></div>
            </div>
            <div id="reszletek">
              <button id="buttonDetails" onClick={handleClick}>
                Details
              </button>
            </div>
            {isShown && (
              <div id="window" onClick={handleClickClose}>
                <div className="details">{obj.id}</div>
                <div className="close">Close</div>
              </div>
            )}
          </div>
        ))}
      </div>
    </>
  );
}
export default App;
Posted
Updated 19-Apr-23 5:29am

1 solution

All your product details share the same state. You need to extract a component with a single product details where each product will contain its own state.
Something like
JavaScript
data.map((obj) => (<ProductDeatils prodct={obj}/>)

In general, it's a good advice not to hesitate and split your application into components as much as possible
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900