user2456977 user2456977 - 2 months ago 11
React JSX Question

React passing state to sibling component

const ChatBox = ({ messages, sendInput }) => {
<Card fluid className={theme} raised style={{ height: '100%' }}>
<ChatLog
messages={messages}
/>

<RecordInput // has internal recording state
sendInput={sendInput}
/>
</Card>
}


My
ChatBox
contains a
ChatLog
and
RecordInput
.

The
ChatLog
contains the list of messages to be displayed.

The
RecordInput
is the user voice recording input to be sent to the
ChatLog
. This component has an internal
recording
state which can be
true
or
false
.

I want to send this
recording
state to the
ChatLog
which is a sibling component.

One solution: I can make the
ChatBox
a class component with
recording
state and pass that to both
ChatLog
and
RecordInput
.. but I would rather not refactor my functionless stateless component ..

Is there another way to do this? Perhaps redux or doing some sort of cloning?

Answer Source

There are multiple options:

  1. Use redux to have a global state, as you already mentioned.
  2. Add RecordInput class the onRecordStatusChange prop that will be called within that component every time the status is changed, and it will tell the parent component (Card) about the new status of the recording. This way you can save the status of the recording both in the parent and the child component, and the parent component can pass this data to other child components (siblings of the RecordInput component).
  3. Use a ref on the RecordInput to check the status of the recording of inside that component (which I don't think is what you want in this specific situation, but you can do this).