I created a website using Next.js with React and really like to declare a js variable to define component styles like this:
const foo = {
fontSize: '12px',
};
And in the render method I do:
render() {
return (
<div style={foo}>bar</div>
);
}
Using ESLint I can quickly find unused styles/variables (if references are gone) and keep the code clean. Hence I do not use <style>
or styled-jsx like this:
render() {
return (
<div>
<style>
.foo {
font-size: '12px';
}
</style>
<div className="foo">bar</div>
</div>
);
}
The problem
The problem with using only js variables instead of <style>
is that I cannot apply media queries to target different screen sizes, so I thought I could fix this using javascript:
render() {
// Bigger font size for smaller devices
if (windowWidth < 768) foo.fontSize = '24px';
return (
<div style={foo}>bar</div>
);
}
I get windowWidth
through this workaround: Get viewport/window height in ReactJS. This works quite well as long as the rendering happens on the client. The problem with this approach is that Next.js will render the view first server-side. At this moment in time, the window/screen size is unknown, hence windowWidth = 0
. Thus, I think that the client has to re-render after receiving the initial rendered page from the server.
Question(s):
How can I force the client to immediately re-render after initial render by the server in order to determine the value of
windowWidth
?Would this be a good practice/solution or would it lead to performance problems or elements flickering?