2

I'm wondering if this is possible and if anyone did something similar before.

I need a way to serialize react component definitions (essentially react classes, or functions...) on the server side and somehow pass them to the client side.

The problem I'm hitting is due to the fact that I'm rendering a set of subcomponents dynamically, based on a dynamic list. Upon a request, I consult a service for a list of URLs, require all the js assets from the list (they happen to be components packaged with umd) and I am able to render the server side content dynamically.

The problem happens on the client side when I hydrate the content. All the components re-render but the previously fetched component disappear from the DOM because the component state is empty (the components available on the server side, although rendered, are not available on the client side). I could of course before the hydration, fetch the list and the components again (similar to the logic on the server side). That, of course, would defeat the purpose of server side rendering these components entirely, so I'm wondering if there is a better way to do what I want. There MUST be a way to send the already available react component definitions from the server side to the client side and save a hop.

Any thoughts? Any help is appreciated

alexg
  • 902
  • 11
  • 37
  • Yes it can be done but don't serialize them, that is pointless. Serve them as JavaScript files and load them dynamically using `await import('api/components/some-component.js')` if you use SystemJS, you can even transpile them dynamically as they arrive. Otherwise, you can run TypeScript or Babel server side as part of the API request to transpile the JSX – Aluan Haddad Oct 25 '18 at 02:40
  • you mean before hydrating? – alexg Oct 25 '18 at 02:41
  • If they need to be populated with data server-side that will be more complex, I've not done that part myself, but I imagine it can be done. Treat them as ordinary modules that are excluded from your bundle. However do you really need to server-side render _these_ components? – Aluan Haddad Oct 25 '18 at 02:44
  • yes, to avoid hops + there are a lot of components on that list. the server is on the same network as the cdn, so fetching *from* the server is fast, fetching from the client is well, unpredictable. Having the server render something, as opposed to nothing is better than having UI pieces appear all over the place and flicker the UI – alexg Oct 25 '18 at 19:49
  • doing the prefetch of the components before hydration works. I'm still curious if there's a way to send the component definitions to the client through I donno... JSON? the server has the definitions, why do they need to be refetched and re-created on the client? – alexg Oct 25 '18 at 19:51

0 Answers0