Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8375

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T12:31:07+00:00 2024-11-28T12:31:07+00:00

Expanding cards with multiple buttons using a single state

  • 60k

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

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; ` 
Enter fullscreen mode Exit fullscreen mode

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; 
Enter fullscreen mode Exit fullscreen mode

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; 
Enter fullscreen mode Exit fullscreen mode

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);     }   }; 
Enter fullscreen mode Exit fullscreen mode

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}/>       ))}` 
Enter fullscreen mode Exit fullscreen mode

If they're the same is expanded is set to true and the card expands and reveals the description.

Image description

Image description

And that is how we target each button.

Project link
https://replit.com/@AlexSalazar1/ExpandAndCollapseButonsAndClosingCards#src/App.js

beginnersjavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.