Tengo una lista de tarjetas. Después de hacer clic en cada tarjeta, quiero que se expandan con un poco más de información. Obtengo las tarjetas del servidor y las mapeo. Para expandir una sola tarjeta, no varias, he creado un índice de edición de estado que verifica la identificación de la tarjeta para que pueda funcionar correctamente y expandir específicamente esa tarjeta. No puedo entender, cómo expando una tarjeta y otra al mismo tiempo. Porque ahora mismo, si hago clic en la tarjeta, la otra que estaba expandida se está colapsando.
const [studentList, setStudentList] = useState(); const [input, setInput] = useState(" "); const [editIndex, setEditIndex] = useState(null); const [suggestions, setSuggestions] = useState(null); const handleExpand = (id) => { setEditIndex((e) => (e === id ? null : id))}; return ( <div className="flex flex-col w-4/5 h-[800px] overflow-scroll scrollbar-hide border bg-white rounded-xl " > <div> {studentList?.map( ({ city, company, email, firstName, grades, id, lastName, pic, skill, }) => ( <div key={uuidv4()} onClick={(e) => handleExpand(id)} className="flex border-b-2 py-2 px-7 xl:px-12 cursor-pointer mb-2 max-h-96 transition transform ease duration-200; " > <div className="flex items-center "> <img src={pic} className="flex items-center border rounded-full object-cover w- [100px] h-[100px]" /> </div> <div className="ml-10 superTest "> <p className="font-bold text-4xl"> {firstName} {lastName} </p> <p>E-mail: {email}</p> <p>Company: {company}</p> <p>Skill: {skill}</p> <p>Average: {grades}% </p> {editIndex === id && ( <div> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> </div> )} </div> </div> ) )} </div> </div> ); } export default Card;En lugar de editIndex , tenga un Set de valores de id de tarjetas expandidas:
const [editing, setEditing] = useState(new Set()); Luego, para expandir/contraer una tarjeta (lamentablemente, Set no tiene un método de toggle ):
const handleExpand = (id) => { setEditing(editing => { // Copy the set editing = new Set(editing); if (editing.has(id)) { // Already editing, stop editing editing.delete(id); } else { // Not editing, start editing.add(id); } return editing; }); }; Para determinar si una tarjeta está expandida, está editing.has(id) :
{editing.has(id) && ( <div> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> </div> )}Intente usar una matriz o mapa de tarjetas expandidas:
const [editIndex, setEditIndex] = useState([]); ... const handleExpand = (id) => { setEditIndex((e) => (e.includes(id) ? e.filter(i => i !== id) : [...e, id])) }; ... {editIndex.includes(id) && ( <div> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> </div> )}Debe indicar con un objeto y mantener las identificaciones de tarjetas expandidas en el objeto. Al usar un objeto en lugar de una matriz, evita el bucle para filtrar la matriz
import React, { useState } from 'react'; function Card() { const [studentList, setStudentList] = useState(); const [editIndex, setEditIndex] = useState({}); const handleExpand = (id) => { setEditIndex((e) => (e === id ? null : id)) setEditIndex({id: !editIndex[id]}); }; return studentList.map((student, index) => <div onClick={() => handleExpand(index)} className={`otherClassNames ${editIndex[index]?"expanded":"collapsed"}`}> {JSON.stringify(student)} // render student data </div> ); } export default Card;Por otro lado, puede utilizar el componente Contraer de la biblioteca Ant Design. Así que dejen el tema del derrumbe de ellos.
https://ant.design/components/collapse/
y otros componentes complicados están disponibles en el uso de la biblioteca deben consultar.