Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!