How to create a micro-frontend with React?
Ragu is completely compatible with React. This article will teach you how to expose a micro-frontend using react. You must have a React project set up. If you don't have one, we recommend you to start one using create-react-app.
Installing dependencies#
You must have both ragu-cli and ragu-server-adapter to expose your micro-frontends.
- Yarn
- NPM
The micro-frontend file#
The micro-frontend file follow the same guidelines described at the Micro-frontends section the
only difference is that when using React you must export a default function that returns a React element.
Create the micro-frontend file.
my-mfe.jsNow use
ragu-clito start the development server:- Yarn
- NPM
Check the micro-frontend live http://localhost:3100/preview
Code Example
The code of the examples above can be found here.
Exposing a React Component#
You also can return a React component.
Code Example
The code of the examples above can be found here.
Receiving Parameters#
The previous example outputs a Hello, World micro-frontend. Let's say, instead of
Hello, World we want to receive the name which the micro-frontend will say Hello to.
Create a micro-frontend file.
my-mfe.jsStart the ragu development server.
- Yarn
- NPM
Open the preview page providing the name query parameter http://localhost:3100/preview?name=Ragu.
Code Example
The code of the examples above can be found here.
Server Side Rendering#
To enable SSR you should provide the --ssrEnabled flag.
With this flag Ragu will start to return the micro-frontend HTML rendered from server.
note
This section describes how to enable SSR at your React micro-frontend. For more information about Ragu and SSR
take a look at the Server Side Rendering section.
The state file#
Let's say you want your micro-frontend to perform an async operation, fetching a request for example. You can use a state file for this purpose.
The state file must export a default function that returns a Promise.
Properties received by the state function are the same described at
Micro-frontend API.
Create the state file
state.jsReceive the
stateinto the micro-frontend function.my-mfe.jsStarts the development server using the
SSRmode.- Yarn
- NPM
Check the micro-frontend live http://localhost:3100/preview?number=1
note
The state is always executed the
server-sideit means that the state will always be null whenSSRis not enabled.Code Example
The code of the examples above can be found here.