I combined code for the lessons 5,6,7,8 for Building Components into one code base for my future reference:
Blockquote
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) => {
console.log(index + 1 + ". " + item);
console.log("Event: ", event);
setSelectedIndex(index); // set selected index
};
return (
<>
List
{items.length === 0 &&
No item found
}{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}
))}
</>
);
}
export default App;
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) => {
console.log(index + 1 + ". " + item);
console.log("Event: ", event);
setSelectedIndex(index); // set selected index
};
return (
<>
List
{items.length === 0 &&
No item found
}{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}
))}
</>
);
}
export default App;
Blockquote