Conditional Rendering on Server Side

不打扰是莪最后的温柔 提交于 2020-01-25 00:29:24

问题


Background
I am using next.js for server side rendering and react.js for client side.

Goal
Want to do conditional rendering on the basis of window size in server side. Like for 200px width render A component and for 400px width render B component.

Problem
In server side, we have no access to the window object and we have no idea about the device our client is using. So AFAIK we cant do conditional rendering on server side.

Thoughts
I have thought of some solutions, but don't know is it possible or not -
1. Send the device info or window object as json with the http request.
2. Don't render the conditional components in server side and re-render (hydrate) them on client side.

But I don't know what is the best practice and what is more efficient than other. New suggestions are also welcome.


回答1:


Consider using next approach:

  1. On server side you can predict device type by parsing user-agent with help of mobile-detect package and pass expected values to an isomorphic HOC created on top of react-sizes which allows to setup "predicted" screen sizes to work on server side.
  2. Wrap your conditional logic with appropriate to your business logic structures with adaptive HOC you've created
  3. ...
  4. Profit

Be aware of at least next cases you should take care of:

  1. Narrow screens of desktop user-agents will be rendered as for desktop, but might start re-rendering on client side, as MatchMedia gonna do its work on client
  2. Any caching layer should include parsed device type into cache key so you will not cache potentially broken layout.



回答2:


You can know if the device is a mobile or not by using this piece of code in your server.js

app.get('*', (req, res) => {
  var ua = req.header('user-agent');
  if (/mobile/i.test(ua)) {
    //mobile code
  } else {
    // desktop code
  }
});

and you can pass this boolean in react and use it




回答3:


I had a few places with these conditions. At the end I decided to only render conditional component on the client side as least problematic solution with smallest overhead.

Other solutions:

If its a component with an important SEO content and you need to render it (make it look a bit better if its rendered on a wrong size till react rerenders component depending on the screen size). Bare in mind this approach can introduce some bugs during rehydratation as react sometimes duplicates div's. You can set a new key for a compont to fix it.

You can also use css for hidding content.



来源:https://stackoverflow.com/questions/55394365/conditional-rendering-on-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!