Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

But also , it is restriction ; communication between two components is restricted in 3 cases :

  1. Parent updates Child :

  2. Child updates parent :

  3. siblings (Brothers) updates each other (brother)


Let's locate your question now.. Your question is about the 3rd case :

The main idea is to make the grand-parent (App) as proxy to transfer communication .


App/\/\||
             ▼      ▼
BoardDashboard|
            ▼ 
Cell

Dashboard.js

reset(event) {
  //.... local calls (concerning Dashboard or its children )// then , external calls (concerning outside Dashboard)if(this.props.onReset) this.props.onReset(event);
}

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

App.js (the 1ˢᵗ grand-parent between [Dashboard, Board>Cell]) :

onDashboardReset(event) {
  this.setState({dashboardIsReset: true})
}

<Dashboard   onReset={this.onDashboardReset} />
<BoarddashboardIsReset={this.state.dashboardIsReset} />

Board.js :

// ... has props  `dashboardIsReset` and forward it to its children (`Cell`) if needed

Post a Comment for "Passing Messages Between Components In React.js"