I combined code for the lessons 5,6,7,8 for Building Components into one code base for my future reference:
import { useState } from "react";
function App() {
let items = [
"New York",
"San Francisco",
"Tokyo",
"London",
"Paris",
"Rome",
"Los Angeles",
];
const [selectedIndex, setSelectedIndex] = useState(-1);
//event handler
const clickHandler =
(index: number, item: String) => (event: React.MouseEvent<HTMLElement>) => {
console.log(index + 1 + ". " + item);
console.log("Event: ", event);
setSelectedIndex(index); // set selected index
};
return (
<>
<h1>List</h1>
{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={clickHandler(index, item)} // Provide a new function that calls your handler with the data you need
>
{item}
</li>
))}
</ul>
</>
);
}
export default App;