A Modular Approach To Building React Components

Ivan Luk
3 min readDec 1, 2020

When building a webpage, sometimes it is tempting to just put everything in one component. Maybe we get carried away when we start coding or maybe we think it is easier for others to understand if we have everything in one component file. However, I do think if you break things down logically into smaller components, it actually will be easier for others to follow your codes. Let me illustrate with an example.

Here is a line of code in the App.js file in my project. I am telling React Router Dom that if the user enter a path /buckets, the component Buckets will be rendered. This is how the page looks like.

If I break down this page into high level elements, it would look like this:<Nav bar>
</Nav bar>
<Header>
</Header>
<Map>
<Marker></Marker>
<Marker></Marker>
…<Marker></Marker>
</Map>

Instead of coding this as one big component, I chose to break it down into two modules. The main Buckets component contains the nav bar, header, and a sub-component that contains the map related items. Here’s the code (JSX is coded using Semantic UI React).

Since nav bar contains it’s own independent behavior, I can include the element here without worrying about confusing the audience. However, if I code the map and marker behavior logic in this component, the code could get complex and it may not be easy for readers to follow. The above codes, on the contrary, clearly indicate to readers that MapBuckets is another element that handles some specific data. In this case, “buckets” is a prop to be accessed in the component. Let’s take a look at the MapBuckets component.

In this component, I am rendering a Google Maps Map element, and within the map itself I am rendering Marker elements from an array passed in via props. It is quite clear to readers that the function of this component is to display the Google Maps with markers created from the props array using the map method. Any functionality required to handle actions on the map can be found in this component code (e.g. the handleClick function when the marker is clicked).

The two components are not exactly substantial in size but by separating them, I can focus on their individual behaviors without worrying about the logic getting convoluted. The MapBuckets component is now also reusable if I decide another page somehow can use this Google Maps with markers.

There is no hard and fast rule on how or when to break down your page into coordinated modules. Next time when a page becomes complex and you are finding yourself writing a lot of functions doing seemingly unrelated things, maybe that is a sign to take a look at breaking it apart into smaller manageable pieces.

--

--

Ivan Luk

Used to manage software development in financial services. Recently acquired skills include full stack development and DNA extraction/sequencing.