'How to call a function in one React component by button click in another component

I am making a pos system and I am trying to make the items appear on the list section when I click on each of them. My problem is that the Items section and the List section are two different components and I can not figure out how to make a click in Items section change the state of the list section.

Items Section:

import Item from "./Item";

function ItemSection() {
  const Items = [{ title: "DOMAIN", cost: 109 }];
  return (
    <div>
         <Item title={Items[0].title} cost={Items[0].cost} onClick={() => this.clickHandler(title, cost)}></Item>
    </div>
  );
}

export default ItemSection;

List Section:

import React, { useState } from "react";

function ListItems(props) {
  const [title, setTitle] = useState(props.title);
  const [cost, setCost] = useState(props.cost);

  const clickHandler = (mTitle, mCost) => {
    setTitle(mTitle);
    setCost(mCost);
  };

  return (
    <div>
      <table>
        <tr>
          <td> {title} </td>
          <td> ${cost} </td>
        </tr>
      </table>
    </div>
  );
}

export default ListItems;

Item:

function Item(props) {

  return (
    <div>
      <button>{props.title}</button>
    </div>
  );
}

export default Item;


Solution 1:[1]

As per my understanding, you've two components: ItemSection and ListItems and you want to call a function in ListItems, that is defined in ItemSection? Is it the correct understanding?

If yes, then you can define your function in ItemSection and send that function as prop in ItemSection

In ItemSection:

    <ListItems sampleFunction = {(e)=>sampleFunction(e)}/>

In ListItems:

    interface Props{
    sampleFunction: Function;
    }

and:

    <button OnClick = {props.sampleFunction}>{props.title}</button>

This is just a pseudo code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthijs