Components are a tool for splitting the page in smaller pieces that are easier to manage and reuse. By breaking the page into smaller parts, we make their implementation simpler.
But at the same time this creates a new challenge: the communication between these small parts.
I’ll take as an example a page managing a list of to-dos. The user is able to see, add, and search for to-dos.
This is how the page looks:
We can split the page in three main components based on their responsibilities:
TodoAddForm: the form for adding a new to-do
TodoSearchForm: the form for searching a to-do
TodoList: the list for displaying the to-dos
We can go even further and make every item in the list have its own component:
For the sake of this analysis, I encapsulate the text-box and button in their own component:
Components are in a Tree Structure
Before analyzing how to communicate between components, we need understand that components are organized in a tree structure. If the framework doesn’t force a root component, then we’ll create one.
Now let’s create the tree structure:
Presentation and Container Components
We can start defining the components’ responsibilities by using the Container and Presentational Pattern.
The presentation components communicate only through their own properties, methods, and events. They are not connected to external communication objects. This makes presentation components easier to understand and more reusable, as they are not coupled to other objects.
The container components are connected to external objects. They listen for events from these objects and do actions. They provide data to the user interface.
I’ll start with only one root container component:
TodoContainer. All the other will be presentation components:
There many means for communication at our disposal. In the end, we need to choose the one that’s appropriate for our situation.
To sum up, these means of communication are :
- Parent → Child: properties, methods
- Child → Parent: events, callbacks
- Child → Child: via parent, domain store, UI store, or global event bus.
In short, two child components can communicate using their closest parent or a shared third object.
Read Functional Architecture with React and Redux and learn how to build apps in function style.
For more on applying functional programming techniques in React take a look at Functional React.