React - list items with options on hover

0 votes
80 views
added Jan 22 in React by lcjr First Warrant Officer (11,970 points)

This is a React component for a list with three items. Each item has a title in the left column and a time in the right column. When you hover over an item, the background turns white, and the time is replaced with options for edit, delete, and share.

The list component

import React, { useState } from 'react';
import './List.css'; // Make sure to create a CSS file (List.css) for styling

const List = ({ data }) => {
  const [hoveredIndex, setHoveredIndex] = useState(null);

  const handleMouseEnter = (index) => {
    setHoveredIndex(index);
  };

  const handleMouseLeave = () => {
    setHoveredIndex(null);
  };

  return (
    <div className="list-container">
      {data.map((item, index) => (
        <div
          key={index}
          className={`list-item ${hoveredIndex === index ? 'hovered' : ''}`}
          onMouseEnter={() => handleMouseEnter(index)}
          onMouseLeave={handleMouseLeave}
        >
          <div className="title">{item.title}</div>
          <div className="actions">
            {hoveredIndex === index && (
              <>
                <span className="action-btn">Edit</span>
                <span className="action-btn">Delete</span>
                <span className="action-btn">Share</span>
              </>
            )}
            {hoveredIndex !== index && <div className="time">{item.time}</div>}
          </div>
        </div>
      ))}
    </div>
  );
};

export default List;

 

CSS file

.list-container {
  display: flex;
  flex-direction: column;
}

.list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ccc;
  transition: background-color 0.3s ease;
}

.list-item.hovered {
  background-color: #fff;
}

.title {
  flex-grow: 1;
}

.actions {
  display: flex;
}

.action-btn {
  cursor: pointer;
  margin-left: 10px;
}

.time {
  margin-left: 10px;
}

 

Include the List component into your parent component

import React from 'react';
import List from './List';

const YourComponent = () => {
  const listData = [
    { title: 'Item 1', time: '10:00 AM' },
    { title: 'Item 2', time: '11:30 AM' },
    { title: 'Item 3', time: '2:45 PM' },
  ];

  return (
    <div>
      <List data={listData} />
    </div>
  );
};

export default YourComponent;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...