Next.js - Anticipated that the server HTML would include a corresponding <div> within <div> tag

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

Answer №1

It's important to note that accessing the window object on a server side is not possible. Therefore, if you need to render something on the server based on the window object, you will have to hardcode these values.

The only reliable information you can use is the user-agent in the request headers, which provides some insight into the device used by the user.

One way to detect the user's device in _app.js is as follows:

const device = deviceDetector.detect(isServer() ? ctx.req.headers['user-agent'] : window.navigator.userAgent)

deviceDetector refers to any type of device detection system that uses the user agent.

Answer №2

If you're curious how I resolved this issue, I decided to move away from responsive design using logic and transitioned to CSS. Below is the updated layout after making some modifications with classes that have the lg prefix. You can find more information in the documentation:

const UpdatedLayout: React.FC<UpdatedLayoutProps> = ({}) => {
  return (
    <div className="mt-12 lg:mt-24 w-5/6 mx-auto flex items-start">
      <div className="w-full flex justify-between items-start">
        <ListPosts className="lg:w-4/6 w-full" />
        <div className="hidden sticky ml-12 w-2/6 lg:flex flex-col">
          <TopCategories className="w-full" />
          <PopularPosts className="mt-4" />
        </div>
      </div>
    </div>
  )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Ajax and jQuery to fetch information from a previous search query

I'm currently utilizing Ajax and jQuery for my chat feature. Some may find it overly complex, but as long as it works, that's all that matters. It's functioning properly on the first friend result, however, not on the others. The issue lies ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

"Troubleshoot the issue of a Meteor (Node.js) service becoming unresponsive

Currently running a Meteor (Node.js) app in production that is experiencing unexplained hang-ups. Despite implementing various log statements, I have pinpointed the issue to a specific method where the server consistently freezes. Are there any tools beyo ...

Scroll with Angular to Move Elements

Is there a way to convert this Jquery Code into an angularJs directive? http://jsfiddle.net/MMZ2h/4/ var lastScrollTop = 0; $("div").scroll(function (event) { var st = $(this).scrollTop(); if (st > lastScrollTop) { $('img').a ...

Mastering the art of combining images and text harmoniously

I am having trouble aligning my lion image and h1 tag side by side. There seems to be an issue but I can't figure out what it is. h2 { width:50%; float:right; padding:30px 0px 0px 0px; margin:0 auto; } .lion { width:10%; float: left; paddin ...

Errors and disruptions caused by SmoothScroll, ScrollMagic, and GSAP triggering glitches, jumps, and crashes

Connecting ScrollMagic with GSAP is not an issue - it works seamlessly. However, I encountered a problem when trying to implement smooth scrolling for my mouse. I added a smooth scrolling plugin to my project from this link: http://www.jqueryscript.net/ani ...

Encountering an issue in the test file when using react-router-dom v6: "The 'history' property is not found on the 'IntrinsicAttributes & RouterProps' type."

Main script: import { useContext, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import AuthenticationContext from './AuthenticationContext'; function HandleOAuthCallbackRoute() { co ...

Version 10.0 of sails is having trouble with an undefined 'schema' when using mysql

i'm currently experimenting with sails js version 0.10.0 using the sails-mysql adapter 0.10.6 I have set up two models: Customer.js module.exports = { connection: 'someMysqlServer', attributes: { name: { type: 'string& ...

Unable to properly shut the sliding-over modal

I have implemented a customized version of the codrops slide & push menu (http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/) to create an overlay on my webpage. However, I am facing difficulty in closing it using another link. Any assistance on ...

Struggling to retrieve the session value using JavaScript in a C# application

Currently, I am attempting to retrieve four values from the session. However, I am only able to fetch two of them, while the other two seem to be missing. As a beginner, I apologize if my question comes across as too simplistic. Within a tree view, I have ...

"Seeking to access the call stack in the VSC debugger? Unfortunately, console.trace() turns out to

When I'm stopped in the VSC debugger, I am unable to retrieve the call stack using console.trace(). https://i.stack.imgur.com/f6jke.png ...

Instead of automatically playing, Youtube videos either remain idle or display suggested videos

I am trying to play a specific moment of an embedded Youtube video using some javascript code. At the specified time, I execute the following code: document.getElementById("video").src= "https://www.youtube.com/embed/...?autoplay=1&start=212"; where ...

Issue with the first-child selector

Is this supposed to work or am I losing my mind? .project.work:first-child:before { content: 'Projects'; } .project.research:first-child:before { content: 'Research'; } <div class="project work"> <p>abcdef</p> ...

Tips for achieving comma-separated user input via ngModel and appending it to an array

I am working on an email template that includes a cc option. I want users to be able to add email addresses with commas separating them and then push them to an array called $scope.notifyCtrl.cc. How can I accomplish this using AngularJS 1.5 and above? mai ...

Unused React import in the index.js file

Just starting to explore the world of reactJS. import React from 'react'; import ReactDOM from 'react-dom'; var App = ()=>{ return <div> Hello !!</div> } ReactDOM.render(<App />, document.getElementById(' ...

Can a Vue component in SFC form be utilized as a mixin?

Consider this scenario, where I have a component created in SFC format: // Parent.vue <template> <div> {{ txt }} </div> </template> <script> export default { name: 'ParentComponent', data() { return ...

Leveraging React's useEffect hook to asynchronously fetch and load data

In my coding scenario, there is a parent component containing a child component which loads data asynchronously. This is what I currently have: <Parent> <AsyncChild data={props.data} /> <Child /> </Parent> Within the AsyncChil ...

Updating textures dynamically for individual faces in a three.js environment

I have been facing a difficult challenge for some time now, struggling to achieve my goal while unsure if I am on the right path. The Objective My current project involves developing a three.js web application that loads JavaScript models and assigns cu ...

Using RadStyleSheetManager for Optimizing CSS Caching

After implementing the RadStyleSheetManager in my master pages using the given code snippet, I noticed a significant improvement in the performance of my web application. In Internet Explorer 8, the number of dynamically generated WebResource.axd files had ...

Activate expansive pop-up windows with primeng's dynamic dialog feature

In my Angular web application, I am using the PrimeNg modal extension to display modal popups. I have successfully passed a component to the modal service with the following code: const ref = this.dialogService.open(LogsComponent, { data: { ...