Naisergic Sharma
3 min readJan 22, 2021

--

Micro Frontend With ReactJS

In this post, we will discuss how to implement Micro Frontend with Reactjs

Micro Frontend is a concept that is being borrowed from the microservice world where the big monolith services are being broken into smaller independent services. Currently when we developed Front end projects all of our code sits at a commonplace and we end up creating a big monolith project.

To overcome this drawback we can think of our application as different independent applications and then integrating all different pieces to get the final app.

To keep this post specific to Micro Frontend, in the following setup I will not be discussing some of the things like setting up of React Project with Webpack, assuming the reader has some basic knowledge.

To demonstrate how to create a Micro Frontend, consider an app that displays some product and its price and it has 2 routes, one is home and the other is “/v2” which will display another version of the product and its price.

Now before going further we will discuss how react inject its dom, in your index.js/main.js (entry file) you provide the Main Container and the id of the div in which react injects the dom.

index.js(entry file)

you define this div inside your HTML file

index.html

So Basically React find a div with id “root” and inject the DOM inside this div and if you inspect your react-app in your browser you will notice that a bundle script is also injected.

So Now think that you have two different react-project one is displaying the Product and the other one is showing the price and they are running independently on the different servers so in our main app we can add 2 different div’s with the id which is being used in those project itself and can inject the js bundle of the projects.

index.html of ProductDisplay
index.html of ProductPrice
index.html of the main project

so now first run your ProductDisplay and productPrice App and then start your main APP then you will see both the project is being run.

Micro Front With React
Product APP
Price APP

Routing also works with the micro frontend.

Routing With Micro FrontEnd

Instead of directly injecting the script in index.html, we can inject the script on componentDidMount as well by writing an injectScript

inject script

so now you can break your application into different independent applications but obviously, you don't want to break the product display and its price into two different applications but instead, you can break the cart, product review.

you can view the code here

--

--