Home > Blockchain >  How to pass throught information parent-children React
How to pass throught information parent-children React

Time:12-21

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?

CodePudding user response:

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.

CodePudding user response:

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)} />
   )
}
  • Related