Search code examples
javascriptreactjsreact-props

React JS pass the data or child component to parent component


Is it possible to pass the data from the child component to the parent component using props?

-Parent component
  --- ItemList component.
  --- DisplatSelect component from the itemList component

I have a list of item in the child component which came from to the parent component, then I want to send the index of the selected data to the other child component located in the parent component.

Can't example well, kindly see the attached screenshot for other references. Thanks a lot!

enter image description here


Solution

  • You can keep the data in the Parent component and use a function to pass the props from the child to the Parent. This concept is called Lifting State Up where you define the state at the highest common ancestor so all the child components are using the same data which in this case is the selecetd item

    function Parent() {
      const [selectedItem, setSelectedItem] = useState(null);
      const data = []; // Your Data
      return (
        <>
          <h1>Your selected Item = {selectedItem}</h1>
          {data.map((item) => {
            <Child item={item} setSelectedItem={setSelectedItem} />;
          })}
        </>
      );
    }
    
    function Child({ item, setSelectedItem }) {
      return <Button onClick={() => setSelectedItem(item.id)}> {item} </Button>;
    }