-->

11/03/2022

React Js Modularity - Breaking a monolith react component into modular components

Earlier in 2017, I have written a few articles on Basics of SharePoint Framework, Use of React JS and React JS component life cycle

But Most of the SPFx web parts I created were task oriented and not application oriented. This means the size of the React components is small. 

Now I am working on a product / application level components which are complex and big in size.

Here is a screenshot of a POC I am currently working.


There are 3 Tabs, in which some tabs has roughly 4 to 5 forms with numerous fields. Now with what ever experience you have with SPFx and ReactJS development, imagine how big this component will be.

If you are dealing with any react component with more than 300 lines of code, you need to think about breaking that monolith into small chunks.

Its just not about no. of lines of code. Its about principle of "Separation of Concerns". I can envision above application as below.

Now question comes to how you going to separate functionality into different ReactJS components still make it work together.
There are 3 ways of doing it.

1. Functions: 
Functions are used to separate small but reusable code that can be called in multiple places. Typical example would be headers and footers that can be written as functions and called in every page. below is the code sample how you do it in React.



2. Sibling Components: 
This means the the components are completely independent of their actions, and there is not data propagation between them. In the above example the components "Information" and "Membership" are sibling components. How do we embed them in UI Component?

Here are the definitions of both Information and Membership components.


Now lets import these components into the UI component.

then this how we embed them in UI markup.

Here is the out come.

3. Parent Child Components:
Now in Template component , I have a Taxonomy picker control. For it to work, I need the Webpart Context. But you cannot find webpart context in child component. I need to send it from UI component.
How do we do that?

Create a constructor in child component , which accepts the properties from parent.

Now pass that webpart Context to Taxonomy picker.


In UI Component, this is how we send the Webpart Context to child component.

Now look at the out put

This is how we break monolith React components modular components and increase maintainability of our applications.

Happy coding !

No comments:

Post a Comment