
react-chain simplifies the process of bootstraping browser, and server rendered React applications with a shared middleware chain. It allows developers to share custom logic with both rendering targets, as well as targeting either one specifically. Additionally, some parts of the browser’s rendering process need only happen once, therefore react-chain middleware is designed around the concept of sessions. Each session wraps the rendering of the app. This allows us to run setup code ahead of, or after the inital, or continous, render process.
Note: react-chain is in active development and the API is subject to change drastically before it hits version
1.0.0
.
Usage
Install as dependency, using the package manager of your choice:
npm install --save react-chain
Create a new file, app.js, and add the following code to it:
// app.js
createReactChain()
will instantiate a new ReactChain instance that can be used to link middleware and perform render on. The example above creates a very simple middleware chain that ends with a middleware that renders a div
, containing the string Hello ReactChain!
. Note that the resulting React element returned from a render is wrapped with an instance of ReactChainProvider
, which gives us access to custom logic which we see later.
Middleware
A react-chain comprises a chain of middleware, that have the following API (typescript type definitions):
The session
object that is passed to the middleware has the following API:
Render
Browser
react-chain exposes a handy method, called startClient
, which accepts two arguments, a react-chain instance, and a dom node to render the app in. This method wraps ReactDOM.render
and adds a refresh method to the session, allowing middleware to trigger a rerender of the application.
Example:
// index.js
Server-side rendering
Server rendering requires a bit more configuration and thus we do not ship a rendering method in this version. This may, or may not change in the future.
Example:
// server.js const server = server server