Listgroup, Fragment, Event, State, Props, Children

This commit is contained in:
2024-08-09 20:30:30 +08:00
parent 9fb34cffdf
commit 915d499c18
11 changed files with 173 additions and 148 deletions
+53
View File
@@ -0,0 +1,53 @@
import { Fragment, MouseEvent, useState } from "react";
interface Props {
items: string[];
heading: string;
// (item: string) => void
onSelectItem: (item: string) => void;
}
function ListGroup({ items, heading, onSelectItem }: Props) {
let itemsLocal = ["Orange", "Apple", "Watermelon", "Banana", "Durian"];
// Hook For State
const [selectedIndex, setSelectedIndex] = useState(-1);
const emptyMsg = items.length === 0 ? <p>No item found</p> : null;
const getEmptyMessage = () => {
return emptyMsg;
};
// Event Handler
const handleClick = (event: MouseEvent, index: number) => {
console.log(event);
console.log("Clicked", items[index], "at index", index);
setSelectedIndex(index);
onSelectItem(items[index]); // Call the onSelectItem callback with the selected item
};
return (
<>
<h1>{heading}</h1>
{getEmptyMessage()}
{items.length === 0 && <p>No item found</p>}
<ul className="list-group">
{items.map((item, index) => (
<li
className={
selectedIndex === index
? "list-group-item active"
: "list-group-item"
}
key={item}
onClick={(event) => handleClick(event, index)}
>
{item}
</li>
))}
</ul>
</>
);
}
export default ListGroup;