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 dependenciesYou must have both ragu-cli
and ragu-server-adapter
to expose your micro-frontends.
- Yarn
- NPM
#
The micro-frontend fileThe 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-cli
to 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 ComponentYou also can return a React component.
Code Example
The code of the examples above can be found here.
#
Receiving ParametersThe 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 RenderingTo 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 fileLet'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
state
into the micro-frontend function.my-mfe.jsStarts the development server using the
SSR
mode.- Yarn
- NPM
Check the micro-frontend live http://localhost:3100/preview?number=1
note
The state is always executed the
server-side
it means that the state will always be null whenSSR
is not enabled.Code Example
The code of the examples above can be found here.