I used to render a component depending on the screen width by writing something like this.
function App(props) {
const [mobile, setMobile] = useState(() => window.innerWidth < 576 ? true : false)
return (
<div>
{
mobile ? <ComponentA /> : <ComponentB />
}
</div >
);
}
But now that I'm using Next.js this gives me several errors due to the window.innerWidth reference. How could I do this? Thanks in advance.
windowis undefined on the server so you'll see an error. You need to do a check likewindow && window.innerWidth < 576window &&will still throw server-side.typeofcan be used to check whether variables have been declared safely, e.g.typeof window !== 'undefined' && window.innerWidth < 576 ? true : false