Tengo una aplicación React en la que me gustaría implementar la funcionalidad cuando el mouse está en la fila adecuada (al pasar el mouse) y luego se muestra un botón para editar y eliminar en la fila correspondiente. Implementé algo, pero cuando el mouse está en una fila, estos botones aparecen en todas las filas.
Este es mi código:
import React from 'react'; const Contact = (props) => { const array = Object.entries(props); const classes = document.getElementsByClassName('btn'); const display = (isShown) => { if (isShown) { for (let i = 0; i < classes.length; i++) { classes[i].style.display = 'block' } } else { for (let i = 0; i < classes.length; i++) { classes[i].style.display = 'none' } } }; return ( <table className="table table-light"> <thead> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Continent/Country</th> <th scope="col">eMail</th> <th scope="col">FreeGuyz</th> <th scope="col">Instagram</th> <th scope="col">Twitter</th> </tr> </thead> <tbody> {array.map((contact, index) => ( <tr onMouseEnter={() => { display(true) }} onMouseLeave={() => display(false)} key={index}> <th scope='row'>{index += 1}</th> <td>{contact[1].name}</td> <td>{contact[1].continentAndCountry}</td> <td>{contact[1].email}</td> <td>{contact[1].accountNameForFreeGuyz}</td> <td>{contact[1].accountNameForInstagram}</td> <td>{contact[1].accountNameForTwitter}</td> <td> <button style={{ marginRight: 5 + 'px' }} className='btn btn-warning' id={contact.id}>Edit</button> <button className='btn btn-danger' id={contact.id} type='submit'>Delete</button> </td> </tr> ))} </tbody> </table> ); }; export default Contact;Me alegraré si alguien puede ayudarme.
Mi sugerencia:
Cree un componente separado para cada fila de la tabla,
Dentro de él, crea un estado que represente isHovered .
Actívelo o desactívelo en mouseenter - mouseleave .
const ContactRow = ({ contact, index }) => { const [isHovered, setHovered] = useState(false); // ... logic return ( <tr onMouseEnter={() => { setHovered(true); }} onMouseLeave={() => setHovered(false)} key={index} > <th scope="row">{(index += 1)}</th> <td>{contact[1].name}</td> <td>{contact[1].continentAndCountry}</td> <td>{contact[1].email}</td> <td>{contact[1].accountNameForFreeGuyz}</td> <td>{contact[1].accountNameForInstagram}</td> <td>{contact[1].accountNameForTwitter}</td> <td> {isHovered && <><button style={{ marginRight: 5 + "px" }} className="btn btn-warning" id={contact.id} > Edit </button> <button className="btn btn-danger" id={contact.id} type="submit"> Delete </button></>} </td> </tr>}A menos que haya una razón por la que necesite hacer esto en JS, recomendaría usar CSS para resolver este tipo de problemas. Solo asegúrese de que puede seleccionar el botón de edit (es decir, dele una clase de edit en este ejemplo):
tr button.edit { display: none; } tr:hover button.edit { display: initial; }