`ReactDOM.renderToString` will render a react element to its initial HTML
This returns a HTML string and should only be used on the server
import App from 'Shared/app'
const appRender = (location, plainPartialState, routerContext = {}) => {
// Create store + redux provider
...
const appHtml = ReactDOMServer.renderToString(<App />)
return (
)
}
appRender.jsx
<html>
<head>
${head.title}
${head.meta}
<link rel='stylesheet' href='${assetPath}/css/styles.css' />
</head>
<body>
<div class="${APP_MOUNT_CONTAINER}">${appHtml}</div>
<script src="${assetPath}/js/bundle.js"></script>
</body>
</html>
HTML to render
Server
import App from 'Shared/app'
// location: the url the server received
// context: properties a component can add to store information
// passed to the component via the staticContext prop
ReactDOM.renderToString(
<StaticRouter location={} context={}>
<App />
</StaticRouter>
);
Client
import App from 'Shared/app'
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
On the server, we populate `window.__PRELOADED_STATE__`
<script>
window.__PRELOADED_STATE__ = ${JSON.stringify(store.getState())}
</script>
appRender.html
On the server, we populate `window.__PRELOADED_STATE__`
// Grab our preloaded state that came from the server
const preloadedState = window.__PRELOADED_STATE__
// create our store using the preloaded state
const store = createStore(
combineReducers({ someStateSlice: someStateSliceReducer }),
{ someStateSlice: preloadedState.someStateSlice }
);
index.jsx
Server
// grab parameters for our html head from the helmet component
const head = Helmet.rewind()
....
<head>
${head.title}
${head.meta}
</head>
....
Client
// TODO: move all this helmet shit to a HoC
import Helmet from 'react-helmet'
....
const title = 'Artist page'
const ArtistPage = () =>
<div>
<Helmet
title={title}
meta={[ { name: 'description', content: 'A tiny app' }, { property: 'og:title', content: title } ]}
/>
...
</div>
export default ArtistPage
😅
import React from 'react'
import styles from './ComponentStyles.css'
export default class StyledComponent extends React.Component {
...
render() {
return (
<header>
<h1 className={styles.someStyle}>🤙🏾🔥Yeaaaaah boiiiii</h1>
</header>
)
}
}
if ( process.env.BROWSER ) {
require('./StyledComponent.css');
}
export default class SomeComponent extends React.Component {
render() {
return (
{🤙🏾🤙🏾🤙🏾}
);
}
}
const hook = require('css-modules-require-hook');
hook({
generateScopedName: '[name]_[local]__[hash:base64:5]',
rootDir: projectDir
});