Basic microfrontend

21 views Asked by At

I'm trying to make a container app which will have small apps inside for example a hello world app. By surfing I found this concept of microfrontend. I'm very new to this concept. Saw youtube videos, but nothing seems to be helpful. can anyone show me how to use it in a very very basic way ?

I'm using npx create-react-app for the containe-app and the child-app

Project directory structure

This is my project structure. Tried these too :

// container-app/src/ContainerApp.js
import React, { useState } from 'react';

function ContainerApp() {
  const [isChildLoaded, setIsChildLoaded] = useState(false);

  // Function to load the child app dynamically
  const loadChildApp = async () => {
    try {
      // Dynamically import the child app's entry point (index.js)
      const { default: childApp } = await import('./child-app/src/index.js');

      // Optionally, you can render the child app directly here or navigate to it.
      setIsChildLoaded(true);
    } catch (error) {
      console.error('Error loading child app:', error);
    }
  };

  return (
    <div>
      <h1>Container App</h1>
      <button onClick={loadChildApp}>Load Child App</button>
      {isChildLoaded && <p>Child App is loaded!</p>}
    </div>
  );
}

export default ContainerApp;

Index.js of container folder

// container-app/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import ContainerApp from './ContainerApp';

ReactDOM.render(
  <React.StrictMode>
    <ContainerApp />
  </React.StrictMode>,
  document.getElementById('root')
);

Child app :

// container-app/child-app/src/App.js
import React from 'react';

function App() {
  return (
    <div>
      <h1>Child App</h1>
      <p>This is the child app!</p>
    </div>
  );
}

export default App;

0

There are 0 answers