Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a JSON file of products and want to put details into divs.

The second div (window) is hidden by default so it needs {isShown && DIV_CONTENT} state.

I just want, that the window div let be in the same map function as the divStyle class div.

git:
GitHub - folza1/react-modulzaro[^]

What I have tried:

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>
          </div>

        {isShown && (
          <div id="window" onClick={handleClickClose}>
            <div className="details">
              Details like obj.title in curly braces
            </div>
            <div className="close">Close</div>
          </div>
          )}
        ))}
      </div>
    </>
  );
}
export default App;
Posted
Updated 6-Jan-23 7:45am

1 solution

The easiest solution is to first create a variable that you will place in your return statement.

What I mean is to create a variable which will hold your current JSX.

Then you can decide if the stuff you return contains the extra div or not.

Very simple example:

JavaScript
let mainDiv = (<div>my stuff </div>);
let extraDiv = (<div> extra stuff</div>);
let targetDivsForReturn = [];

render(){
     targetDivsForReturn.push(mainDiv);
     if (isShown){
        targetDivsForReturn.push(extraDiv);
     }
     return (<>
        {targetDivsForReturn}
      </>)   
}
 
Share this answer
 
v2

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