score:0

import React, { useState } from "react";

// this is just sample data to work with - equivalent to the data you get from Firebase
const sampleCardsArray = [
  {
    id: 0,
    name: "Card 1",
    color: "red",
    description: "This is card 1",
  },
  {
    id: 1,
    name: "Card 2",
    color: "blue",
    description: "This is card 2",
  },
  {
    id: 2,
    name: "Card 3",
    color: "green",
    description: "This is card 3",
  },
];

// component for all cards
export const AllCards = () => {
    // this state is used to store the INDEX of the card that is currently expanded
  const [expandedCard, setExpandedCard] = useState(null);
  return (
    <div>
      {sampleCardsArray.map((card, index) => (
        <OneCard
          card={card}
          key={card.id}
          // this prop passes the boolean value of whether the card is expanded or not
          isExpanded={expandedCard === index}
          // this prop receives the index of the card that is expanded and sets the state
          expandCard={() => setExpandedCard(index)}
        />
      ))}
    </div>
  );
};

// component for one card
// We only show the fields: name and color. We show the description when the card is clicked
export const OneCard = ({ card, isExpanded, expandCard }) => {
  return (
    <div>
      <h1>{card.name}</h1>
      <h2>{card.color}</h2>

      {
        // showing expand button only when card is not expanded
      }
      {isExpanded ? (
        <p>{card.description}</p>
      ) : (
        <button onClick={() => expandCard()}>Expand card</button>
      )}
    </div>
  );
};


Related Query

More Query from same tag