For a live demonstration, please click here
In my current project, I am experimenting with creating a simple layout that adjusts based on the user's screen size. Specifically, on mobile devices, only the latest posts should be displayed. On desktops, the left column should contain the posts while the right column will showcase the top categories and most popular posts.
Here is how the layout is structured:
const IndexLayout: React.FC<IndexLayoutProps> = ({}) => {
const cols = useScreenType()
return cols === '2-cols' ? (
<div className="w-full flex justify-between items-start">
<ListPosts data-comp="ListPosts" className="w-4/6" />
<div className="sticky ml-12 w-2/6 flex flex-col">
<TopCategories data-comp="TopCategories" className="w-full" />
<PopularPosts data-comp="PopularPosts" className="mt-4" />
</div>
</div>
) : (
<ListPosts data-comp="ListPosts" className="w-full" />
)
}
This is the custom useScreenType
hook being used:
import { useMediaQuery } from 'react-responsive'
export const useScreenType = () => {
const is2Cols = useMediaQuery({ minWidth: 1300 })
const is1Cols = useMediaQuery({ minWidth: 800 })
if (is2Cols) {
return '2-cols'
}
if (is1Cols) {
return '1-cols'
}
return 'fullscreen'
}
However, I keep encountering this error message:
Warning: Expected server HTML to contain a matching <div> in <div>.
// Error details continue below...
The issue seems to stem from the fact that the useScreenType
hook is unable to determine the width due to the absence of the window
object on the server. How can I resolve this issue? Additionally, not only am I getting an error message, but the rendering of the HTML appears distorted.
When rendered as '2-cols', the final output looks something like this:
<div class="flex flex-col justify-start items-start w-full">
<div class="mt-6 w-full"></div>
<div class="mt-4 flex items-center cursor-pointer transform transition hover:scale-105 text-sm">
// Inner content goes here...
</div>
</div>
Note: The framework being used is Next.js v10.2.0
You can access the codebase on GitHub