fable-compiler / fable-react

Fable bindings and helpers for React and React Native
MIT License
273 stars 67 forks source link

FunctionComponent.Lazy and SSR #222

Closed mvsmal closed 2 years ago

mvsmal commented 2 years ago

The code below has a comment saying that React.lazy doesn't support SSR, thus FunctionComponent.Lazy result in an empty div on server side. Is there any reason you don't just return the f function directly instead?

https://github.com/fable-compiler/fable-react/blob/master/src/Fable.React.FunctionComponent.fs#L36-L55

type FunctionComponent =
#if !FABLE_REPL_LIB
    /// Creates a lazy React component from a function in another file
    /// ATTENTION: Requires fable-compiler 2.3 or above
    /// Pass the external reference directly into the argument (avoid pipes)
    static member inline Lazy(f: 'Props -> ReactElement, fallback: ReactElement): 'Props -> ReactElement =
#if FABLE_COMPILER
        let elemType = ReactBindings.React.``lazy``(fun () ->
            // React.lazy requires a default export
            (importValueDynamic f).``then``(fun x -> createObj ["default" ==> x]))
        fun props ->
            ReactElementType.create
                ReactBindings.React.Suspense
                (createObj ["fallback" ==> fallback])
                [ReactElementType.create elemType props []]
#else
        fun _ ->
            div [] [] // React.lazy is not compatible with SSR, so just use an empty div
#endif
#endif
alfonsogarciacaro commented 2 years ago

Ah, you're probably right. I guess I was thinking that usually you want to trigger lazy after a user interaction not on the first render. But now that you mention it, it's true there may be situations in SSR when you want to render the contents of Lazy.

It should be fine to change it as you say. Do you want to send PR? (I can also make the change myself as it's an easy one.)