2

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.

3 Answers 3

4

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.
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

1 Comment

yap, but I need to get the device resolution. Only the device type wont help me :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.