A Bdux middleware for Universal (isomorphic) JavaScript.
- Render the same React app on both the client and the server.
- Seamlessly resume states from the server to the client.
To install as an npm package:
npm install --save bdux-universalimport * as Universal from 'bdux-universal'
import { applyMiddleware } from 'bdux'
applyMiddleware(
Universal
)Then place <UniversalStates /> in root component to render serialised states.
import React from 'react'
import { UniversalStates } from 'bdux-universal'
const App = () => (
<>
<UniversalStates />
</>
)
export default AppServer Root can be created using createRoot(createElement, stores = {}).
createElementis a function to create the application root element.storesis an object of dependent stores.
Then use renderToString or renderToNodeStream function to render the application into HTML through ReactDOMServer.
DefaultRoot.renderToString(req, res)Example of a server root:
import React from 'react'
import App from '../components/app-react'
import MessageAction from '../actions/message-action'
import MessageStore from '../stores/message-store'
import { resetLocationHistory, LocationStore } from 'bdux-react-router'
import { createRoot } from 'bdux-universal'
export const createElement = ({ dispatch }, req) => {
resetLocationHistory(req.path)
dispatch(MessageAction.message('Message from Server'))
return <App />
}
export default createRoot(
createElement, {
location: LocationStore,
message: MessageStore
}
)Please checkout Universal for a example setup with Express and webpack.
Server Root can be created using createAsyncRoot(createAsyncActions, createElement, stores = {}).
createAsyncActionsis a function to create a Bacon stream which produce a single array of asynchronous actions.createElementis a function to create the application root element.storesis an object of dependent stores.
Then use renderToString or renderToNodeStream function to render the application into HTML through ReactDOMServer asynchronously.
DefaultRoot.renderToString(req, res)
.map(renderHtml(res))
.subscribe(() => Bacon.noMore)Example of an asynchronous server root:
import R from 'ramda'
import React from 'react'
import Bacon from 'baconjs'
import App from '../components/app-react'
import WeatherAction from '../actions/weather-action'
import WeatherStore from '../stores/weather-store'
import CountryCodesAction from '../actions/country-codes-action'
import CountryCodesStore from '../stores/country-codes-store'
import { createAsyncRoot } from 'bdux-universal'
export const createAsyncActions = () => (
Bacon.when([
CountryCodesAction.load(),
WeatherAction.searchWeather('NZ', 'Auckland').last()
],
// map arguments to an array.
(...args) => args
)
export const createElement = () => (
<App />
)
export default createAsyncRoot(
createAsyncActions,
createElement, {
countryCodes: CountryCodesStore,
weather: WeatherStore
}
)Please checkout Async for a example setup with Express and webpack.