Passing functions via Props

main
Gerardo Marx 2 weeks ago
parent 3c3b4472e2
commit 9cd6f1ebcc

@ -3,9 +3,13 @@ import ListGroup from "./components/ListGroup";
function App() { function App() {
let items = ["New York", "San Francisco", "Tokyo", "London"]; let items = ["New York", "San Francisco", "Tokyo", "London"];
const handleSelectItem = (item: string) => {
console.log(item)
}
return ( return (
<div> <div>
<ListGroup items={items} heading="Cities"/> <ListGroup items={items} heading="Cities" onSelectItem={handleSelectItem}/>
</div> </div>
); );
} }

@ -3,10 +3,10 @@ import { useState } from "react";
interface Props { interface Props {
items: string[]; items: string[];
heading: string; heading: string;
onSelectItem: (item: string) => void;
} }
function ListGroup({items, heading}: Props) { function ListGroup({ items, heading, onSelectItem }: Props) {
const [selectedIndex, setSelectedIndex] = useState(-1); const [selectedIndex, setSelectedIndex] = useState(-1);
return ( return (
@ -22,7 +22,10 @@ function ListGroup({items, heading}: Props) {
: "list-group-item" : "list-group-item"
} }
key={item} key={item}
onClick={()=>setSelectedIndex(index)} onClick={() => {
setSelectedIndex(index);
onSelectItem(item);
}}
> >
{item} {item}
</li> </li>

Loading…
Cancel
Save