Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react.js trigger event inside another component upon button click

I am building my first web app with react. Its a chat with multiple chat rooms. This is what I got visually:

enter image description here

Now I simply want to click on "open" on any room and display the messages within that chatroom inside the white div on the right currently saying "HI MOM".

But these two are different components.

This is the list of chatrooms:

export default function ChatRoomList({param1}) {
    const [chatRooms, setChatRooms] = React.useState([]);
    React.useEffect(()=>{
      (async () => {
          var x = await getChatRoom(param1)
          console.log(x)
          setChatRooms(x)
      })()
    },[])  
  
      return  (
          <div className='chatRoomView'>
               {chatRooms.map((chatRoom , index) => {
                  return (
                      <ul >
                        <li key={index}>
                            <table>
                                <tr>
                                    <td>
                                        ChatroomID: {chatRoom.chatIDFromTableChats}
                                        <br></br>
                                        Username:  {chatRoom.userNameUser2}
                                    </td>
                                    <td>
                                        <Button variant="contained" onClick={() => loadChatRoomFromID(chatRoom.chatIDFromTableChats)}>open</Button>
                                    </td>
                                </tr>
                            </table>
                        </li>
                      </ul>                   
                  )             
               })}
          </div>
      );
    }
  
    function loadChatRoomFromID(ID) {
       alert(`chatRoomID: ${ID}`);
    }

Upon button click I am currently just able to open an alert displaying the ID of the clicked element.

Here is component two:

export default function ChatMessages() {

function loadMessages(ID){
    // HELP NEEDED?!
}

    return  <div class='mainChatView'>HI MOM</div>;
      
}

As you can see, there is a function called "loadMessages()" but it doesnt do anything since it needs to get the ID param passed and then start loading the messages of each room.

The connection from one to the other component is missing and so far, no answer i read about didnt fail miserably for me...

Can someone give me a working code example and explain what is happening?

Thank you!

like image 982
innom Avatar asked Sep 05 '25 13:09

innom


1 Answers

In React, data can only be passed down from parent to child via props (see note at the end for more detail on this), not from sibling to sibling. This doesn't mean, however, that siblings cannot cause updates in each other, it just means that you need to restructure your code a bit so that data flows down properly.

You can store the active chatroom ID in the parent of the list and detail views and let the list view update the ID while the detail view uses the ID to load messages.

Here's a simple example:

function Chat() {
    const [activeRoomID, setActiveRoomID] = React.useState(null);

    const onActiveChange = React.useCallback((id) => {
        setActiveRoomID(id);
    }, []);
    
    return (
        <div>
            <ChatRoomList onActiveChange={onActiveChange}/>
            <ChatMessages id={activeRoomID}/>
        </div>
    )
}

function ChatRoomList({ onActiveChange }) {
    // ...

    return (
        <div>
            {chatRooms.map(chatRoom => (
                <div key={chatRoom.chatIDFromTableChats}>
                    <div>ChatroomID: {chatRoom.chatIDFromTableChats}</div>
                    <Button onClick={() => onActiveChange(chatRoom.chatIDFromTableChats)}>Open</Button>
                </div>
            ))}
        </div>
    )
}

function ChatMessages({ id }) {
    // load messages for `id` and display
}

Notice that the data only flows down from the <Chat> component to its children.

Note about data only flowing from parent to child: There are additional complexities to this statement. As this example shows, children can also pass data up to their parents but only by using a callback function provided via props, so the React-specific parts still only allow data to flow down. Also the context API allows for passing data to deep descendants (not just children).

like image 162
Henry Woody Avatar answered Sep 08 '25 03:09

Henry Woody