Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing messages between components in React.js

I had a few questions about the communication between React.js components. This is in context to without the use of redux. Here is what my component hierarchy looks like.

       App
      /  \
     /    \
    |      |
    ▼      ▼
 Board   Dashboard
   |
   ▼ 
 Cell

Below are a few assumptions/patterns that i use for components to communicate.

  1. If we need to pass messages from a parent component to child components we do that using props. For example, while creating a Board we pass rows, cols as props.

    <Board rows={5} cols={5} />
    
  2. If we need to pass messages from a child component to parent components we do it by passing a callback. For example we pass a play() callback from Board to Cell. Within Cell, we set the onClick handler to be the passed callback i.e. play().

    <Cell onClick={this.props.play(this.props.id)} />
    
  3. The open question i had was how can be pass messages between sibling components (example Dashboard to Cell). One use-case is resetting my Board component when a reset button within Dashboard component is clicked. Here is what reset button within Dashboard looks like. My question is once the reset message reaches App component, whats the best practice to pass it down to Board?

    <input type="button" value="reset" onClick={this.props.reset} />
    

Would be great to get some feedback on 1 and 2. Also, the best practice for 3.

like image 376
noi.m Avatar asked Sep 14 '26 21:09

noi.m


1 Answers

Redux

This is the exact reason why Redux is so cool. If you're using Redux, then all of these components have one single thing in common; they're all reading their values from the application state. The flow that I would use, is as follows:

  1. User clicks on the reset button that lives inside the Dashboard Component

  2. The function associated with that click does only one thing. Dispatches a "RESET_BOARD" action

  3. In the reducer, the RESET_BOARD action resets the state for the board.

  4. When the re-render occurs, the board is passed in props, just like before, only empty state is passed into it.

No Redux

If you've got no redux at hand, then the callback approach from the parent is the sensible way to go. If you're maintaining state in the App component, the App then resets its state and triggers a re-render manually. This will cause the Board to be re-rendered with different props.

like image 147
christopher Avatar answered Sep 16 '26 09:09

christopher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!