Conditional Rendering On Server Side
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.
Answer
Consider using next approach:
- 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.
- Wrap your conditional logic with appropriate to your business logic structures with adaptive HOC you've created
- ...
- Profit
Be aware of at least next cases you should take care of:
- 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
- Any caching layer should include parsed device type into cache key so you will not cache potentially broken layout.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?