passing value to parent component react, pass data to multiple parent components [2022]

    By: Thad Mertz
    2 years ago

    Passing value to parent component react, pass data to multiple parent components. Yes we can pass values to parent and parent of parent here is how

    So We have 3 components


    1st.   App.js  // Here we have the list data present
    2nd.  List.jsx
    3rd.  Card.jsx // Here we display the each list item and delete from here
    


    So if we delete from Card.jsx then we have to go to List.jsx and then App.js to update "List". Here is how we do it


    In Card.jsx

    <div className="position-absolute top-0 end-0 p-2">
         <a href="#/" onClick={() => deleteListItem(listItem.id)}>
             <FaTimes/> 
         </a>
    </div>
    

    Now here we have on click deleteListitem where we pass the id. This "deleteListitem" is not function defined in "Card.jsx" instead it is a prop comming from "List.jsx".

    const Card = ({listItem, deleteListItem}) => {  // Getting prop in Card.jsx
    

    Here is How we passed from "List.jsx"

    <div className="col-md-8 offset-2 mt-5">
         {list.map((item) => (
              <Card 
                   key={item.id} 
                   listItem={item}
                   deleteListItem={deleteListItem}/>
         ))}
    </div>
    

    Now here we are passing "deleteListitem" as a prop to "Card.jsx" also we are getting same "deleteListitem" as a prop from APP.js to List.jsx that is why we passed prop value as "deleteListitem".

    const List = ({list, deleteListItem}) => { // Getting prop in List.jsx
    

    Now lets see how we are pssing values from App.js

    return (
        <>
          <Header/>
          <List list={listData} deleteListItem={deleteCurrentItem}/>
        </>
      );
    

    See we are passing prop to "List.jsx" with a value coming from a function "deleteCueentItem"

    So function can be in App.js

    const deleteCurrentItem = (id) => {
        console.log(id); // here we can add code for deleting clicked list item.
      }
    
    
      return (
        <>
          <Header/>
          <List list={listData} deleteListItem={deleteCurrentItem}/>
        </>
      );