This is a simple base component class for true server-side rendering with emulation of server interaction.
It is intended for use with class components and without any external state management libraries like Redux. Basically it's intended for pure setState()-based code.
Algorithm
- Write code in such a way that it still works if DOM is not available
- Make your components inherit from
SSRComponent:- Use
doRenderinstead ofrender - Use
initinstead ofconstructor - Everything else stays the same
- You can additionally override
serializeStateandunserializeStateif your state isn't directly JSON-serializable
- Use
- Implement SSR:
- Declare
store = {} - Render your component using
react-test-rendererwithstore={store}in props - Make sure your code tracks all fetch() requests (server interactions) during render
- And of course mock fetch() (or analogue) to use internal server-side calls
- Wait until all fetch() requests complete
- Re-render until the component stops issuing additional requests
- Render HTML using
renderToHtml(testRenderer.toJSON()) - Serialize state using
JSON.stringify(SSRComponent.serializeStore(store))
- Declare
- Hydrate the rendered HTML in your frontend code:
- Call
ReactDOM.hydrate()instead ofReactDOM.render() - Pass serialized state from the last step of SSR to your top-level SSRComponent
- Call
virtualRender.js
Simpler (but less compatible) alternative to react-test-renderer.
USAGE:
import virtualRender from 'virtualRender.js';
const options = {};
let html = virtualRender(<Component {...props}>, options);
while (options.shouldUpdate)
{
html = virtualRender(<Component {...props}>, options);
}
Author and License
Author: Vitaliy Filippov, 2021+
License: Dual-license MPL 1.1+ or GNU LGPL 3.0+ (file-level copyleft)
Description
Languages
JavaScript
100%