In this blog post, we will explore how to create a React website using Micro Frontends, specifically React Micro Frontends. The website will consist of three applications: The user’s App, Header App, and Container App. The Container App will integrate the User and Header Apps, resulting in a seamless single web application.
Install react-app-rewired
Update package.json
Update index.js fileCreate React Applications –
Let’s create three react applications,
npx create-react-app container npx create-react-app users npx create-react-app header
Let’s create a Constant add array of users,
export const arrUsers = [ { "userID": 1, "userName": "Shubham", "userDetail": "Hello Shubham.", }, { "userID": 2, "userName": "Suraj", "userDetail": "Discover a ways to develop secure react application.", }, { "userID": 3, "userName": "Ronak", "userDetail": "Discover a set of React best coding practices.", } ]
Let’s do code for Users Listing, Create a file User.js
import React, { useState, useEffect } from "react"; import {arrUsers} from './Constant'; import { Link } from "react-router-dom"; import "./App.css"; function App() { return ( <div className="container mt-5"> <div > { arrUsers.map((user, index) => { return ( <div className="col-xs-12 col-sm-12 col-md-6 col-lg-4 col-xl-4 mb-5"> <div className="card"> <Link to={{pathname: `/userdetail/${user.userID}`, id: user.userID, item: user}} > <div class="card-body"> <h5 class="card-title">{`#${user.userID}`}</h5> <p class="card-text">{user.userName}</p> <p class="card-text">{user.userDetail}</p> </div> </Link> </div> </div> ) }) } </div> </div> ); } export default App;
Users are located at url.com/users, So we need to set up react-router-dom and history.
npm install react-router-dom history
To see user detail we need to set up code for UserDetail, create a file UserDetail.js
import React, { useState, useEffect } from "react"; import {arrUsers} from './Constant'; import "./App.css"; function UserDetail(props) { const [userDetail, setUserDetail] = useState({}); useEffect(() => { const userID = parseInt(props.match.params.userId); const index = arrUsers.findIndex((user) => user.userID === userID); if (index !== -1){ setUserDetail(arrUsers[index]) } }, []); return ( <div className="container mt-5"> <div className="row"> <div className="card"> { Object.keys(userDetail).length > 0 && <> <p>{`#${userDetail.userID}`}</p> <p>{userDetail.userName}</p> <p>{userDetail.userDetail}</p> </> } { Object.keys(userDetail).length === 0 && <p>We're sorry, this user is not found!</p> } </div> </div> </div> ); } export default UserDetail;
Finally, We have Constant, Users, and UserDetail. Now Let’s do code for Users, UserDetail routing. Replace the App.js code with the following,
import React, { useState, useEffect } from "react"; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import { createBrowserHistory } from "history"; import Users from './Users'; import UserDetail from './UserDetail'; import "./App.css"; const defaultHistory = createBrowserHistory(); function App({ history = defaultHistory }) { return ( <Router> <Switch> <Route exact path="/" component={Users} /> <Route exact path="/userdetail/:userId" component={UserDetail} /> </Switch> </Router> ); } export default App;
Now, it’s time to run the application. We can see the list of Users and on the press of the user, it redirects users to user detail.
Here, We simply add a header div to demonstrate Header Application. So, let’s add all required dependencies.
npm install react-router-dom history
Let’s modify the code for App.js
import React from "react"; import { createBrowserHistory } from "history"; import "./App.css"; const defaultHistory = createBrowserHistory(); function App({ history = defaultHistory }) { return ( <div> <p>MINDTRANS (Header Application)</p> </div> ); } export default App;
Now, let’s run the application, It will show a Simple Header.
So, we have two applications ready, Users Application – where we do code for Users Listing, and Header Application – Where we do code for Showing Header In Application.
Now, it’s time to set up our Container Application which actually uses/merges both Header and Users Application into our Container Application (Our Main Website)
Let’s add react-router-dom, history to Container Application. After that let’s update the code for App.js
import React, { useState } from "react"; import { BrowserRouter, Switch, Route } from "react-router-dom"; import { createBrowserHistory } from "history"; import MicroFrontend from "./MicroFrontend"; import "./App.css"; const defaultHistory = createBrowserHistory(); const { REACT_APP_HEADER_HOST: headerHost, REACT_APP_USERS_HOST: userHost, } = process.env; function Header({ history }) { return <MicroFrontend history={history} host={headerHost} name="Header" />; } function Users({ history }) { return <MicroFrontend history={history} host={userHost} name="Users" />; } function UserDetail({history}) { return ( <div> <MicroFrontend history={history} host={userHost} name="Users" /> </div> ); } function Home({ history }) { return ( <div className="container"> <Header /> <Users /> </div> ); } function App() { return ( <BrowserRouter> <React.Fragment> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/userdetail/:userId" component={UserDetail} /> </Switch> </React.Fragment> </BrowserRouter> ); } export default App;
Think, about how my Container app knows about Header Application and Users Application. Let’s set it up one by one.
Setup Web Application Port
Container Application – Port 3000
Header Application – Port 3001
Users Application – Port 3002
To do this, update package.json,
Container Application
"scripts": { "start": "PORT=3000 react-app-rewired start", },
Header Application
"scripts": { "start": "PORT=3001 react-app-rewired start", },
Users Application
"scripts": { "start": "PORT=3002 react-app-rewired start", },
Now, Create a .env file in the root directory of the Container Application,
REACT_APP_HEADER_HOST=http://localhost:3001
REACT_APP_USERS_HOST=http://localhost:3002
You know, React App bundles entire applications to main.js, where we have functions to render, mount, and unmount components.
Render Function Name: render{ApplicationName}
UnMount Function Name: unmount{ApplicationName}
So, Your Users App looks like this,
renderUsers unmountUsers
Same way, Header App looks like,
renderHeader unmountHeader
Let’s create a MicroFrontend.js file in Container App, which has business logic for mount, unmount components.
import React, { useEffect } from "react"; function MicroFrontend({ name, host, history }) { useEffect(() => { const scriptId = `micro-frontend-script-${name}`; const renderMicroFrontend = () => { window[`render${name}`](`${name}-container`, history); }; if (document.getElementById(scriptId)) { renderMicroFrontend(); return; } fetch(`${host}/asset-manifest.json`) .then((res) => res.json()) .then((manifest) => { const script = document.createElement("script"); script.id = scriptId; script.crossOrigin = ""; script.src = `${host}${manifest.files["main.js"]}`; script.onload = () => { renderMicroFrontend(); }; document.head.appendChild(script); }); return () => { window[`unmount${name}`] && window[`unmount${name}`](`${name}-container`); }; }); return <main id={`${name}-container`} />; } MicroFrontend.defaultProps = { document, window, }; export default MicroFrontend;
As you can see MicroFrontend component will take name, host, and history as params. See the fetch function which fetches the asset-manifest.json from the host and creates a script object using the main.js and it will use the render function to mount components.
Let’s install the react-app-rewired package which overrides the build config without ejecting the app.
npm install react-app-rewired
Create config.overrides.js in the root directory of the user’s application and add the following code.
module.exports = { webpack: (config, env) => { config.optimization.runtimeChunk = false; config.optimization.splitChunks = { cacheGroups: { default: false, }, }; config.output.filename = "static/js/[name].js"; config.plugins[5].options.filename = "static/css/[name].css"; config.plugins[5].options.moduleFilename = () => "static/css/main.css"; return config; }, };
Now, let’s update the scripts section of the package.json file,
"scripts": { "start": "PORT=3002 react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-app-rewired eject" },
And final step in the Users Application is to update index.js,
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; window.renderUsers = (containerId, history) => { ReactDOM.render( <App history={history} />, document.getElementById(containerId), ); }; window.unmountUsers = containerId => { ReactDOM.unmountComponentAtNode(document.getElementById(containerId)); }; if (!document.getElementById('Users-container')) { ReactDOM.render(<App />, document.getElementById('root')); }
Finally, We run the Container App (Our Main Web Application)
In conclusion, we have learned how to build a React website using micro frontends, a modern approach to web development. We created three applications – Users App, Header App, and Container App, demonstrating the effectiveness and benefits of using React micro frontends.
Need a React.js developer for your micro frontend project? Hire one today and start building high-quality, scalable, and performant applications that meet your business needs!
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork