React 18

Last Updated: 9/25/2023

Passing Function via Props/Events

  • We need a mechanism to notify the consumer or the parent of the component when some event happens
  • Pass function via props to the component
  • To view errors/problems VS Code > View > Problems

Parent Component

const handleSelectItem = (item: string) => console.log(item);
const  cities  = ["Chennai", "Bangalore", "Trivandrum", "Hyderabad"];

  return (
    <div>
      <ListGroup
        items={items}
        heading="Cities"
        onSelectItem={handleSelectItem}
      ></ListGroup>
    </div>
  );

Child Component

interface Props {
  items: string[];
  heading: string;
  onSelectedItem: (item: string) => void;
}

function ListGroup({ items, heading, onSelectedItem }: Props) {
  const [selectedIndex, setSelectedIndex] = useState(-1);

  return (
    <>
      <h1>{heading}</h1>
      {items.length === 0 && <p>No Items</p>}
      <ul className="list-group">
        {items.map((item, index) => (
          <li
            className={
              selectedIndex == index
                ? "list-group-item active"
                : "list-group-item"
            }
            key={item}
            onClick={() => {
              setSelectedIndex(index);
              onSelectedItem(item);
            }}
          >
            {item}
          </li>
        ))}
      </ul>
    </>
  );
}