How to define routing for react Micro front end application in Single Spa

1k views Asked by At

I have created a react micro front end application in single spa using the command create-single-spa. Inside the singleSpaReact method, the root component is mentioned.

const lifecycles = singleSpaReact({
  React,
  ReactDOM,
  Router,
  rootComponent: Root,
  errorBoundary(err, info, props) {
    // Customize the root error boundary for your microfrontend here.
    return null;
  },
});

But the react micro application itself have couple of pages. But I don't understand how to define the routing inside the singleSpaReact method. Can anyone help me on this.

1

There are 1 answers

0
vince On

I had the same issue of you and I finally managed this :

I define my singleSpaReact :

import React from 'react';
import ReactDOMClient from 'react-dom/client';
import singleSpaReact from 'single-spa-react';
import Layout from './Layout';
import { contentDomElementGetter } from '../dom-utils';


const reactLifecycles = singleSpaReact({
  React,
  ReactDOMClient,
  rootComponent: (Layout as any),
  domElementGetter: contentDomElementGetter,
});

export const bootstrap = [
  reactLifecycles.bootstrap,
];

export const mount = [
  reactLifecycles.mount,
];

export const unmount = [
  reactLifecycles.unmount,
];

And I defined my Routes in My Layout component :

import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { Header } from './components/Header';
import "bootstrap/dist/css/bootstrap.min.css";
import Home from './pages/Home/Home';
import Reservations from './pages/Reservations/Reservation';
import Tickets from './pages/Tickets/Ticket';
import Cvtheque from './pages/Cvtheque/Cvtheque';

export default class Layout extends React.Component{
  render(): React.ReactNode {    
    return (
      <>
        <BrowserRouter>
          <Header />
            <div>
              <Routes>
                <Route path="/home" element={<Home/>} />
                <Route path="/reservations" element={<Reservations/>}></Route>
                <Route path="/tickets" element={<Tickets/>} />
                <Route path="/cvtheque" element={<Cvtheque/>} />
              </Routes>
            </div>
        </BrowserRouter>
      </>
    );
  }
};

Be aware that I managed this with react-router-dom V6 but if you are with under V6, use Switch instead of Routes