Opening a single element in an array with useState

Viewed 169

I have a mapped list that contains another component that is also mapped. (https://stackblitz.com/edit/rowmaptest?embed=1&file=LaneInfo.jsx) What I'm trying to do is toggle a single row to show the data from the subcomponent.

LaneInfo.jsx

import React, { useState, useEffect } from "react";
import data from "./data.js";
import CarContainer from "./CarContainer";

const LaneInfo = () => {
  const laneData = data.lanes;
  const [showLanes, setShowLanes] = useState(false);

  return (
    <>
      {laneData.map(lane => (
        <>
          <div className="lane" onClick={() => setShowLanes(!showLanes)}>
            <div className="space" key={lane.name}>
              <div>{lane.name}</div>
              <div>{lane.type}</div>
            </div>
          </div>

           {showLanes && <CarContainer data={lane.cars} />}
        </>
      ))}
    </>
  );
};
export default LaneInfo;

with the onClick function, the idea is to hide the div that has been clicked.

However, as you can see in my demo when I click the row both items either open or close.

I think that it will require me to get the unique id of the row from Data.js since this is the way I mapped the rows in , but I haven't been able to figure it out yet.

1 Answers

You might be better creating a separate Lane component and have it manage its own state:

import React, { useState, useEffect } from "react";
import data from "./data.js";
import CarContainer from "./CarContainer";

const Lane = ({
  lane
}) => {
  const [showLane, setShowLane] = useState(false);

  return (
    <>
      <div className="lane" onClick={() => setShowLane(!showLane)}>
        <div className="space" key={lane.name}>
          <div>{lane.name}</div>
          <div>{lane.type}</div>
        </div>
      </div>
      {showLane && <CarContainer data={lane.cars} />}
    </>
  );
};

const LaneInfo = () => {
  const laneData = data.lanes;

  return (
    <>
      {laneData.map(lane => (
        <Lane lane={lane} />
      ))}
    </>
  );
};
export default LaneInfo;
Related