Sometimes, however, you kind of need more. Sometimes you want to use an entirely different layout for mobile devices.
Think an app that needs to have three columns at the same time on the desktop, and tabs on mobile devices.
That would be a helluva “fun” to manage with media queries alone: there are entirely different components at play. A grid on the desktop, and tabs on the phone.
What do we even do about it?..
Let’s imagine we already knew which layout to render. What would the render() method of the top-level component look like?
It would look like an if-else!
Nothing too fancy, but that’s all we need!
Now comes the fun part. How do we determine which layout to render?
We could query window.innerWidth in render, and see if the screen is small enough to display the tabs.
That looks simple! Unfortunately, there is an issue with the code above. It assumes window width to be static — get it once and render the appropriate layout. The reality of the web is different, of course.
If you resize your browser, the app won’t re-render, because it doesn’t know something has changed.
And yet, something clearly did change.
The only way the dimensions of the page change is if a user resizes the browser (or rotates their phone.) Our browsers are kind enough to give us a simple event whenever the size of the page changes.
store the window width in state, and have render use that.
forceUpdate is usually a sign that our data model isn’t quite right. The latter, however, is perfectly in line with React’s dom = render(state, props) equation.
Now render is simply a function of state, and we use the event listener to update our state.