Expanding cards with multiple buttons using a single state 
Tags: beginners, react, webdev, javascript
Published: 2022-02-05 19:18:18

This week while at work i was tasked with creating a page with multiple buttons on a set of varying cards. Each card at the click of a button would expand the card revealing more information on that card.

The task itself seemed trivial, create a set of cards and then add buttons, the problem is hooking up a whole bunch of dynamically made buttons to a single state causes the onClick function to fire for all of the buttons at the same time. 

_Here in this example ill be showing how to create a bunch of dynamically generated buttons and controlling the state of each button._ 


What our App looks like
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3xepcwph7d6nayuaavqu.png)

The three main things we need  to solve this problem 

1. the index of the button
2. the id of the item being placed into the button 
3. Reactive state to change as the user clicks on a button

Here is the data that will be passed into a Card component                                                                                                                        

```
const ButtonExpandData = [
  {
    id: 0,
    name: "Thomas anderson",
    description: "Progrrammer, Martial artist, Chirst Figure",
  },
  {
    id: 1,
    name: "Kratos",
    description: "Father,God of War, Greek Pantheon",
  },
  {
    id: 2,
    name: "James Marshall Hendrix",
    description: "Blues Guitar Player, Army Vet, Legend",
  },
];

//export this file as raw data to use
export default ButtonExpandData;
`
```

Here is our App component which will receive the Data and pass it into our Card component

```
import React, { useState } from "react";
import "./App.css";
import Card from "../src/components/Card";
import ButtonExpandData from "./data/ButtonExpandData";
import TodoListData from "./data/TodoListData";
import Header from "../src/components/Header";
import TaskCard from "../src/components/TaskCard";
function App() {

  const [selected, setSelected] = useState(null);
  let onExpand = (id) => {
    console.log("what am i before", selected);
    if (id === selected) {
      setSelected(null);
    } else {
      setSelected(id);
      console.log("what am i after", selected);
    }
  };

  const [todos, setTodos] = useState(TodoListData);

  const deleteTask = (id) => {
    setTodos(todos.filter((item) => item.id !== id));
  };

  return (
    <>
      <Header />
      <div className="container">
        {ButtonExpandData.map((obj,index) => (
        <Card  id={obj.id} name={obj.name} description={obj.description} isExpanded={index === selected} onExpand={onExpand}/>
      ))}
        {/* {todos.map((obj, index) => (
          <TaskCard key={index} id={obj.id} Task={obj.Task} handleDelete={deleteTask} />
        ))} */}
      </div>
    </>
  );
}

export default App;
```

And Finally here is the Card Component itself

```
import React from "react";
import PropTypes from "prop-types";
function Card({ name, id, description, isExpanded, onExpand }) {
  return (
    <div className="card">
      Name: {name}
      <div>
        <button
          className="btn btn-primary"
          style={{ paddingLeft: "10px" }}
          onClick={() => onExpand(id)}
        >
          click
        </button>
        <br />
        {isExpanded && `description: ${description}`}
      </div>
    </div>
  );
}

Card.propTypes = {
    name: PropTypes.string,
    id: PropTypes.number,
    description: PropTypes.string,
    isExpanded: PropTypes.bool
  };
  

export default Card;
```


Here is the flow of the data, the App component passes down ButtonExpandData with a map, creating a unique button at each iteration. Each object in this array contains an id a name and a description. which are passed down, we also pass down a boolean called isExpanded and onExpand. **Notice that we are also using the index property with the map function, more on this in a second**


` <div className="container">
        {ButtonExpandData.map((obj,index) => (
        <Card  id={obj.id} name={obj.name} description={obj.description} isExpanded={index === selected} onExpand={onExpand}/>
      ))}`

In the card component As soon as the user clicks on a button an event is fired, the onClick sends back up the id of the current item into a function called onExpand. Here we utilize the hook, we created called [selected,setSelected]=useState(null)

Since the default value for the hook is null, meaning our card is current not expanded set selected will fire the else statement setting the id to the id of the current card that was chosen in the event.

```
const [selected, setSelected] = useState(null);
  let onExpand = (id) => {
    console.log("what am i before", selected);
    if (id === selected) {
      setSelected(null);
    } else {
      setSelected(id);
      console.log("what am i after", selected);
    }
  };
```

back in the map, isExpanded now checks the value of our hook selected and then looks at the index. 
```
` <div className="container">
        {ButtonExpandData.map((obj,index) => (
        <Card  id={obj.id} name={obj.name} description={obj.description} isExpanded={index === selected} onExpand={onExpand}/>
      ))}`
```
If they're the same is expanded is set to true and the card expands and reveals the description.  

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sns2apt5adic8wxsui8j.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ow7kt9qaz1uac6s29wj6.png)

And that is how we target each button.

**_Project link_**
https://replit.com/@AlexSalazar1/ExpandAndCollapseButonsAndClosingCards#src/App.js