How can we display different html elements or components based on the size of the device? In react, a package called react-responsive can be used.But in Next, in every component that I use this package, ssr does not run on that component. What do you usually do for this? After all, many times the things that are present in, for example, the Windows display are very different from the things that should be displayed on the mobile phone, and other html codes should be used.
how can i use components based on device size?
766 Views Asked by javad kh At
2
There are 2 best solutions below
0

Since NextJs is server side rendered, Server has no way to know what screen size it is sending the generated html to.
Now 'useEffect' comes to the rescue, since useEffect will only run on client side.
We can use it to get the screen size type once the page is loaded on the browser.
You can use 'react-device-detect' in the following manner.
import { isMobile } from 'react-device-detect';
// declare a state
const [stateMobile, setState] = useState(false);
useEffect(() => {
if (!isMobile && typeof window !== 'undefined') {
setState(stateMobile);
} else {
setState(!stateMobile);
}
}, []);
Then in your return
return (
<>
{isMobile ? (
<div> Mobile html here </div>
) : (
<div> Desktop html here </div>
)}
</>
);
Use this method in you app.js file once and pass it as props to layout. Rather than using useeffect in each component.
Ok, so if i have understood your question you're trying to render a page with all devices-related components but show (with css) only the current device's component.
My approach would be:
In you page component:
Said that, of course you can adapt this code into a custom hook to make it reusable by just doing:
So that you can use it in your page component like this: