Reputation: 57
I am developing an app, that has three room containers/components: available, applied, joined.
After clicking: 'Apply' for room, or 'Remove' I wanted to post some data to my server and, on the front-end side, wanted to update my UI.
So in order to avoid unnecessary requests to my server (refetching data), what I wanted to achieve is to trigger a listener function in the other component, that would pass some data (room) to it and will add/remove room from the list.
Now, the serious question is - how could I achieve it? Does even React provide some built-in listener pattern? Or is there any other possible solution to this case?
If not, would a good solution be, to pass a function in props add/remove (room) to all three components from the parent component, and then pass as an argument room data and to which component should it be passed in?
I have a very little experience in React and it is hard for me to evaluate, which way would be the best.
Upvotes: 0
Views: 41
Reputation: 311
First of all, your plan to centralize the logic in a parent component (instead of each child component calling its own methods) is 100% correct. This way state management can be consolidated into one common place.
One approach is to define an addRoom()
and a removeRoom()
method in your parent component:
addRoom(roomName) {
//update your local state...
//make external requests...
}
removeRoom(roomName) {
//update your local state...
//make external requests...
}
To each child component, you pass props for addRoom()
, removeRoom()
, and the current state:
<ChildOne
addRoom={this.addRoom}
removeRoom={this.removeRoom}
roomState={yourStateObject}
/>
<ChildTwo
addRoom={this.addRoom}
removeRoom={this.removeRoom}
roomState={yourStateObject}
/>
<ChildThree
addRoom={this.addRoom}
removeRoom={this.removeRoom}
roomState={yourStateObject}
/>
Inside each of your child components, you have access to the common/shared state, and you have the ability to call addRoom()
and removeRoom()
, which will cause the parent component to update that common/shared state, which in turn trickles down to all the child components.
Each child component can choose to make use of whatever parts of the shared state that it needs to.
When a child component needs to make a call to addRoom()
or removeRoom()
, it passes the name or id of the room as an argument:
<div onClick={this.props.addRoom.bind(null, 'A')}>Add Room A</div>
<div onClick={this.props.addRoom.bind(null, 'B')}>Add Room B</div>
Upvotes: 2