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

Problem with padding in Firefox when using jQuery's css() methodInconsistent behavior with padding property in

It has come to my attention that Firefox (specifically v19.0.2) is encountering an issue with the jQuery css() function when attempting to retrieve an element's padding. While using .css('padding-left') seems to be a workaround, it would be ...

Unleashed placement and drifting

Is it possible to style this layout without specifying an exact height for "Element 1"? Code Element1 { positon: relative; width: 100%; height: auto; /* Avoiding specific height */ } Inner1 { position: absolute; top: xyz px; left: xyz px; } Inner2 { po ...

What is the best way to incorporate text animation into a website using Cascading Style Sheets (CSS)?

Is there a way to make my text flash twice per second? I attempted to create animated text, but it didn't work out! ...

Issue with utilizing Vuejs variable in Google Maps Matrix API function

Having trouble accessing a Vue.js variable in a function using the Google Maps Matrix API. I am trying to use the Google Distance Matrix API to calculate the distance between two locations. I have declared a variable globally and changed it within a functi ...

Guide on developing a personalized validation system with Vuetify regulations for verifying the presence of an item

I'm currently working on my first CRUD web app using Vue 2 + Vuetify, but I've hit a roadblock while trying to add validation to a form. Specifically, I need to ensure that no item with the same title already exists in the database. You can view ...

What is the process for generating an index.d.ts file within a yarn package?

I'm facing an issue with creating the index.d.ts file for my yarn package. Here is my configuration in tsconfig.json: { "include": ["src/**/*"], "exclude": ["node_modules", "**/*.spec.ts"], " ...

Tips for verifying the functionality of this component---Is there anything

Assistance is needed to test this component using the expect library with karma and mocha. import React from 'react'; import {Clock} from 'Clock'; import {CountdownForm} from "CountdownForm"; import {Controls} from "Controls"; export ...

Integrating a custom domain with a dynamic subdomain in a Next.js app hosted on Vercel, which is already using a

My Next.js app is deployed on Vercel, rendering subdomain-specific content and my domain is already linked to the project. Project Deploy URL: *.mysite.com For example, when John visits john.mysite.com, he sees content specific to his profile. The same g ...

Passing an empty JSON object through Ajax requests

To Whom it May Concern (I am simply attempting to meet the "please add more detail" requirement) Upon sending data to the server as shown below, the body appears empty. Server // Route for POST method app.post('/pass', function (req, res) { ...

Developing a React-based UI library that combines both client-side and server-side components: A step-by-step

I'm working on developing a library that will export both server components and client components. The goal is to have it compatible with the Next.js app router, but I've run into a problem. It seems like when I build the library, the client comp ...

Performing API requests at regular intervals

Apologies for the beginner question, I am new to the world of React. I have multiple components where I need to make API calls at intervals to keep the lists updated. In Angular, I used to create a service that would broadcast events at intervals using ...

Achieving perfect alignment of two elements using flexbox: centering one and aligning the other to the right

Can you help me with aligning two elements to the center and right edge using flex? I am trying to achieve a layout similar to the image. XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX CSS Styles .flex{ display: flex; justify-content: space-between; align-i ...

Is it possible to load modal content using ajax bootstrap pagination without having to refresh the main page?

Whenever I utilize the bootstrap modal and pagination for modal content, clicking the next/prev button causes the entire page, including the main window, to reload. Here are the scripting lines: $("#ajax_process_page").html("<%= escape_javascript(rend ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

Retrieve information from a local API using Next.js

While working with Next.js api today, I encountered an issue. I needed to fetch data from my internal API in getStaticProps. However, the documentation advises against fetching local API directly in getStaticProps and instead suggests importing the functio ...

Issue encountered when setting up Webpack for a React application: the configuration.output.path value of "./" is not an absolute path and causing errors

Recently, I was following an online tutorial to create my first app in ReactJS. The process involved manual package installations using npm in node. However, after completing the setup, I encountered an issue when trying to run npm start. The error message ...

personalizing material-ui component styles – set select component color to be pure white

I am looking to implement a dropdown menu using material-ui components (refer to https://material-ui.com/components/selects/). To do so, I have extracted the specific component from the example: Component return <div> <FormControl variant="outli ...

Creating an executable JAR for your Next.js application: A step-by-step guide

Is there a way to ensure that my Next.js file can run seamlessly on any computer without the need for reinstallation of all modules? In my folder, nextjs-node, I have the following subfolders: components lib public node_modules page style package.json I ...

Discover the ultimate guide to harmonize IE 9 with the ingenious Bootstrap Multiselect plugin developed by davidstutz

I've come across an amazing plug-in developed by David Stutz that allows for a Bootstrap and jQuery multi-select options list. Here are some resources: Check out the source code on Github Find documentation and examples here This plug-in works fla ...

Encountered a connection error while attempting to establish a connection in Node.js

Every time I try to execute the code, I encounter this error message: throw new Error('Most middleware (like ' + name + ') is no longer bundled with express and must be installed separately ^ Error: Most middleware(like BodyParser) is ...