single-spa / single-spa-react

Single-spa lifecycles helper for React applications
https://single-spa.js.org/docs/ecosystem-react.html
MIT License
227 stars 63 forks source link

Add option to use a function as renderType #131

Closed MarcusResell closed 3 years ago

MarcusResell commented 3 years ago

Added the possibility to use renderType as a function. This enables apps to determine at runtime if they should use e.g., hydrate or render which does change for some applications (for example server-side rendered ones). Setting hydrate as a constant for SSR apps produce a bug whenever the users entry-point to the site is not server-side rendered, as normal routing towards this app will not hit the server and the DOM will not have SSR content when the app bootstraps, which in turn produces an error message similar to this when reactdom.hydrate() is called (taken from isomorphic.microfrontends.app):

Warning: Expected server HTML to contain a matching <div> in <div>.
    in div (created by Pr)
    in Pr (created by _r)
    in t (created by t)
    in t (created by _r)
    in _r (created by rootComponent)
    in Ar (created by rootComponent)
    in ze (created by rootComponent)
    in O (created by rootComponent)
    in rootComponent

When used as a function, the renderType can be used for example like this, where it would let the developers decide when and if it should hydrate or render:

getRenderType = (): 'hydrate' | 'render' => {
    const shouldHydrate = document
        ?.getElementById('single-spa-application:@org/the-app')
        ?.hasChildNodes();
    return shouldHydrate ? 'hydrate' : 'render';
};

const lifecycles = singleSpaReact({
    React,
    ReactDOM,
    rootComponent,
    renderType: getRenderType,

Also added render as a possible ENUM value as stated in the docs https://single-spa.js.org/docs/ecosystem-react/#options and fixed a small typo

joeldenning commented 3 years ago

Released in https://github.com/single-spa/single-spa-react/releases/tag/v4.6.0

joeldenning commented 3 years ago

Documented in https://github.com/single-spa/single-spa.js.org/pull/497