User
User

Reputation: 35

How to pass throught information parent-children React

I have a chat with the following structure:

<div className='messages-container'>
    <ChatSidebar/>
    <SelectedChat/>
</div>

I want to select the corresponding room in the chat sidebar in order to chat with that specific user.

However, for that I'd need the information of that user in the SelectedUser component. I've learnt that I can't pass information in between components that are at the same level, so I'd need to pass that information to the parent and that will broadcast to the rest.

How can that be accomplished?

Upvotes: 0

Views: 37

Answers (2)

Dmitriy Zhiganov
Dmitriy Zhiganov

Reputation: 1128

You can use the Lifting State technique.
In your case, it might look like this:

// MainComponent.jsx
const [selectedUser, setSelectedUser] = useState(user)
return (
  <>
  <SelectedUser selectedUser={selectedUser} setSelectedUser={setSelectedUser}/>
  <div className='messages-container'>
      <ChatSidebar/>
      <SelectedChat selectedUser={selectedUser}/>
  </div>
  </>
)

Or, if you can't put both components in the same parent component, you can use Context to access selectedUser from components in different locations.

Upvotes: 2

Amin charoliya
Amin charoliya

Reputation: 606

Although this is not recommended but you can define SelectedUser in parent component.

const [SelectedUser, setSelectedUser] = useState(null);

Now, pass SelectedUser and setSelectedUser like:

<ChatSidebar SelectedUser={SelectedUser} setSelectedUser={setSelectedUser}/>

In ChatSidebar Component:

const ChatSidebar = ({SelectedUser, setSelectedUser}) {
    return(
        <button onClick={ () => setSelectedUser(newID)} />
   )
}

Upvotes: 1

Related Questions