Failure to display React component on screen

I have developed a React microfrontend application consisting of two sub-apps rendered through the container/ project. Both sub-apps render perfectly in isolation on localhost:8083. However, when attempting to view them via localhost:8080/dashboard, I am presented with nothing but a white screen. What's even more puzzling is that there are no errors appearing in the terminal, console, or network requests.

Below is an excerpt from my webpack.dev.js file located in the container/ directory:

const { merge } = require("webpack-merge");
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const commonConfig = require("./webpack.common");
const packageJson = require("../package.json");

const devConfig = {
  mode: "development",
  output: {
    publicPath: "http://localhost:8080/",
  },
  devServer: {
    port: 8080,
    historyApiFallback: true,
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "container",
      remotes: {
        marketing: "marketing@http://localhost:8081/remoteEntry.js",
        auth: "auth@http://localhost:8082/remoteEntry.js",
        dashboard: "dashboard@http://localhost:8083/remoteEntry.js",
      },
      shared: packageJson.dependencies,
    }),
  ],
};

module.exports = merge(commonConfig, devConfig);

I have thoroughly examined this configuration and can't seem to locate any issues.

The next snippet shows the content of webpack.common.js residing within the container/ folder:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react', '@babel/preset-env'],
            plugins: ['@babel/plugin-transform-runtime']
          },
        },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html'
    }),
  ]
}

Similarly, no apparent issues were found upon reviewing the above setup.

Furthermore, here is the code from my components/DashboardApp.js file inside the container/ directory:

import { mount } from "dashboard/DashboardApp";
import React, { useRef, useEffect } from "react";
import { useHistory } from "react-router-dom";

export default ({ onSignIn }) => {
  const ref = useRef(null);
  const history = useHistory();

  useEffect(() => {
    const { onParentNavigate } = mount(ref.current, {
      initialPath: history.location.pathname,
      onNavigate: ({ pathname: nextPathname }) => {
        const { pathname } = history.location;

        if (pathname !== nextPathname) {
          history.push(nextPathname);
        }
      },
      onSignIn,
    });

    history.listen(onParentNavigate);
  }, []);

  return <div ref={ref} />;
};

Lastly, a look at my container/src/App.js:

import React, { lazy, Suspense, useState } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import {
  StylesProvider,
  createGenerateClassName,
} from "@material-ui/core/styles";

import Progress from "./components/Progress";
import Header from "./components/Header";

const MarketingLazy = lazy(() => import("./components/MarketingApp"));
const AuthLazy = lazy(() => import("./components/AuthApp"));
const DashboardLazy = lazy(() => import("./components/DashboardApp"));

const generateClassName = createGenerateClassName({
  productionPrefix: "co",
});

export default () => {
  const [isSignedIn, setIsSignedIn] = useState(false);

  return (
    <BrowserRouter>
      <StylesProvider generateClassName={generateClassName}>
        <div>
          <Header
            onSignOut={() => setIsSignedIn(false)}
            isSignedIn={isSignedIn}
          />
          <Suspense fallback={<Progress />}>
            <Switch>
              <Route path='/auth'>
                <AuthLazy onSignIn={() => setIsSignedIn(true)} />
              </Route>
              <Route path='/dashboard' component={DashboardLazy} />
              <Route path='/' component={MarketingLazy} />
            </Switch>
          </Suspense>
        </div>
      </StylesProvider>
    </BrowserRouter>
  );
};

If anyone notices anything amiss or has encountered a similar issue before, please share insights as to why this particular component fails to render through the container/, unlike the other identical sub-apps.

Answer №1

As the complexity of an application increases, attention to detail becomes crucial. In my container/src/App.js file, I had a path="/dashboard" specified, but the dashboard/src/App.js file did not contain it, and instead looked like this:

import React from "react";
import { Switch, Route, Router } from "react-router-dom";
import {
  StylesProvider,
  createGenerateClassName,
} from "@material-ui/core/styles";
import Dashboard from "./components/Dashboard";

const generateClassName = createGenerateClassName({
  productionPrefix: "da",
});

export default ({ history }) => {
  return (
    <div>
      <StylesProvider generateClassName={generateClassName}>
        <Router history={history}>
          <Switch>
            <Route exact path='/' component={Dashboard} />
          </Switch>
        </Router>
      </StylesProvider>
    </div>
  );
};

After making the following change:

import React from "react";
import { Switch, Route, Router } from "react-router-dom";
import {
  StylesProvider,
  createGenerateClassName,
} from "@material-ui/core/styles";
import Dashboard from "./components/Dashboard";

const generateClassName = createGenerateClassName({
  productionPrefix: "da",
});

export default ({ history }) => {
  return (
    <div>
      <StylesProvider generateClassName={generateClassName}>
        <Router history={history}>
          <Switch>
            <Route exact path='/dashboard' component={Dashboard} />
          </Switch>
        </Router>
      </StylesProvider>
    </div>
  );
};

The content is now displayed within the parent container.

Answer №2

The contentBase parameter is required for proper functioning.

devServer: {
    contentBase: path.join(__dirname, "dist"),
    port: 3002,
  },
  output: {
    publicPath: "http://localhost:3002/",
  },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to insert an object at a particular position within an array containing numerous nested objects?

This is the given Object: [ { "id": "1709408412689", "name": "WB1", "children": [ { "id": "1709408412690", "n ...

Trouble creating Blog pages with Next.js and Sanity

I am currently in the process of integrating Sanity with Next.Js for the first time, as I want to add a blog section to my personal website. Everything seems to be working fine during development, but when I try to deploy or build the project, an error occ ...

Getting started with TinyMCE in Nuxt: A step-by-step guide

I need to incorporate this script into my Nuxt code: <script> tinymce.init({ selector: "#mytextarea", plugins: "emoticons", toolbar: "emoticons", toolbar_location: "bottom", menubar: false ...

Can I find a better approach to optimize this code?

How can I refactor this code to move the entire DB query logic into a separate file and only call the function in this current file? passport.use( new GoogleStrategy({ clientID: googleId, clientSecret: clientSecret, callbackURL: ...

Determining the size of an image prior to uploading it in a React

The solution for this issue can be found using vanilla JavaScript here To clarify, instead of using alert(), my goal is to store the dimensions in the state object. How can I adapt this code into a React component utilizing the OnChange() event handler? ...

What is the best way to access nested objects in React Native?

Here is the JSON data I am working with: [ { id: 51, name: 'Boat Neck Blouse', image: { id: 669, date_created: '2018-08-27T10:05:39', date_created_gmt: '2018-08-27T10:05:39', date_modified ...

Angular Material Sidenav fails to cover the entire screen while scrolling

https://i.stack.imgur.com/32kfE.png When scrolling, the Sidenav is not expanding to take up 100% of the screen and it continues to scroll along with the page content. <div layout="column"> <section layout="row" flex> <!-- siden ...

Manipulate your table data with jQuery: add, update, delete, and display information with ease

When adding data dynamically to the table and attempting to edit, the checkbox value is not updating. This issue needs to be resolved. You can view the code in action on jsFiddle here on JSFiddle ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

Tips for postponing the execution of inline javascript

Main page <script> $.ajax({ type: 'GET', url: 'ajax.php', context: document.body, success: function(data) { $("#content").html(data); } }); </script> <div id="content"></div> Ajax ...

Retrieving and storing state in session storage with React

My webpage features a sidenav with expansion panels that can be opened and closed. I am currently working on setting the state to keep track of which expansion panel is open. However, when I click on one of the items in the sidenav, I get redirected to a ...

Tips on creating a slow and gradual border animation that unfolds smoothly

I am looking to create an animation effect on a border, gradually revealing it like in this Codepen example. However, my specific requirements are: The previous line should not be removed, but rather shown along with the new border. The border color ...

Initiate a CSS animation only when a different animation has completed

I am trying to create a sequence of animations using 2 squares. I want the animation for the red square to start only after the blue square's animation is complete. How can I achieve this cycle of animations? .box { width: 100px; height: 1 ...

Transferring information from a service to an AngularJS controller

I have a service that retrieves data from a URL provided as a parameter, and it is functioning correctly. However, when attempting to pass this data to a controller's $scope in AngularJS, I am not receiving any data. var app = angular.module("Recib ...

The userscript will keep the window open as long as it remains inactive

Hello everyone, I'm excited to join the StackOverflow community and dive into userscripts for the first time! Putting aside any unnecessary details, I'm encountering a small issue with a script I recently created. (function () { $("#enbut"). ...

Error in Winston: Unable to determine the length of undefined property

I encountered an issue with my Winston Transport in the express backend of my MERN app. The error message reads: error: uncaughtException: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefi ...

How to manually highlight a row in Material UI's xgrid

As someone with 10 years of experience in HTML UI, I am new to Material UI and React. Currently, we are utilizing the XGrid component with rows and columns. The issue I am facing is that when hovering over rows, they highlight by turning light blue. Howeve ...

Store the output of the function in a variable

Here is a script that was provided to me: <div id="container1"> <script> var script = document.createElement("script"); script.type = "text/javascript"; script.text = 'document.write(xmlDoc.getElementsByTagName("INFO") ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...

When setting up Webpack with TypeScript, an error is encountered related to imports

Recently, I attempted to convert my Webpack configuration from JavaScript to TypeScript but encountered numerous difficulties in the process. To kick things off, I created a basic webpack configuration file with some parts missing. Here is how my webpack.c ...