Building Scalable Applications with React Micro Frontends

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,

  • Users (Website Users App)
  • Header (Website Header)
  • Container (Actual Website, Where we merged User & Header)
npx create-react-app container
npx create-react-app users
npx create-react-app header

User Application 

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.

Header Application

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.

Container 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;

Hire Our Expert React.js Developers

SetUp Micro Frontends

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.

SetUp Micro Frontends for Users Application

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'));

}

Setup Microfrontends for Header Application

  • Install react-app-rewired
  • Update package.json
  • Update index.js file

Finally, We run the Container App (Our Main Web Application)

coma

Conclusion

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!

Keep Reading

Keep Reading

Mindbowser is excited to meet healthcare industry leaders and experts from across the globe. Join us from Feb 25th to 28th, 2024, at ViVE 2024 Los Angeles.

Learn More

Let's create something together!