Passing Messages Between Components In React.js
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:
User clicks on the reset button that lives inside the Dashboard Component
The function associated with that click does only one thing. Dispatches a "RESET_BOARD" action
In the reducer, the RESET_BOARD action resets the state for the board.
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 :
Parent updates Child :
Child updates parent :
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"