When I compile and run my React components in Next.js, the HTML code is not displaying correctly as certain parts are in the

Trying to explain this may be a bit tricky, so I'll primarily use images and share the HTML code from the inspector. Essentially, in my HTML code, I have two completely separate sections that are divided by curly braces and conditions. Strangely, when the web app is first loaded or reloaded, these two elements sometimes merge together. What I mean is that one element contains the sub-elements of the other. This should not be happening at all. I even added console.logs to double-check which item should be displayed, and despite confirming that ITEM A should be displayed, it ends up showing ITEM B with additional elements from ITEM A mixed in. It's incredibly confusing for me and probably for you too, so I'll just leave the code here for reference.

This code pertains to a navigation component with a Sidebar that remains visible on desktop screens but changes to a navbar with a menu icon on mobile devices. Clicking the menu icon expands the sidebar and pushes the content accordingly.

import React, { useState } from "react";
import { useMediaQuery } from "react-responsive";
import {
    BellIcon,
    ChatAlt2Icon,
    CogIcon,
    MenuIcon,
} from "@heroicons/react/outline";

export const Sidebar: React.FC = ({ children }) => {
    const [isOpen, setOpen] = useState(false);
    const isLarge = useMediaQuery({ query: "(min-width: 768px)" });

    console.log(isLarge);

    return (
        <div className={"flex flex-row w-screen h-screen"}>
            {/* Sidebar starts */}
            {(isOpen || isLarge) && (
                <div
                    id="sidebar"
                    className={"relative w-64 bg-gray-800 h-screen"}
                >
                    <div className="flex flex-col justify-between">
                        <div className="px-8">
                            <ul className="mt-12"></ul>
                        </div>
                        <div
                            className="px-8 border-t border-gray-700"
                            id="bottom-bar"
                        >
                            <ul className="w-full flex items-center justify-between bg-gray-800">
                                <li className="cursor-pointer text-white pt-5 pb-3">
                                    <BellIcon
                                        className="icon icon-tabler icon-tabler-bell"
                                        width={20}
                                        height={20}
                                        viewBox="0 0 24 24"
                                        strokeWidth="1.5"
                                        stroke="currentColor"
                                        fill="none"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                    ></BellIcon>
                                </li>
                                <li className="cursor-pointer text-white pt-5 pb-3">
                                    <ChatAlt2Icon
                                        className="icon icon-tabler icon-tabler-bell"
                                        width={20}
                                        height={20}
                                        viewBox="0 0 24 24"
                                        strokeWidth="1.5"
                                        stroke="currentColor"
                                        fill="none"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                    ></ChatAlt2Icon>
                                </li>
                                <li className="cursor-pointer text-white pt-5 pb-3">
                                    <CogIcon
                                        className="icon icon-tabler icon-tabler-bell"
                                        width={20}
                                        height={20}
                                        viewBox="0 0 24 24"
                                        strokeWidth="1.5"
                                        stroke="currentColor"
                                        fill="none"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                    ></CogIcon>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            )}
            {/* Sidebar ends */}

            <div className="flex flex-col w-full h-full">
                {/* mobile navbar starts */}
                {!isLarge && (
                    <div
                        id="mobile-nav"
                        className="flex h-16 w-full relative bg-gray-800 flex-row items-center p-3"
                    >
                        <div className="cursor-pointer text-white pt-5 pb-3">
                            <MenuIcon
                                className={"icon icon-tabler icon-tabler-bell"}
                                width={30}
                                height={30}
                                stroke="currentColor"
                                fill="none"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                onClick={() => {
                                    setOpen(!isOpen);
                                    console.log(isOpen);
                                }}
                            ></MenuIcon>
                        </div>
                    </div>
                )}
                {/* mobile navbar ends */}

                <div className="flex w-full h-full rounded relative">
                    {children}
                </div>
            </div>
        </div>
    );
};

To see what's going wrong visually, check out this video. As shown, upon a fresh reload, the ID clearly indicates that the mobile nav, which shouldn't be visible (confirmed via log statements), is being displayed. But oddly, the navbar appears with elements from the sidebar - even though the mobile navbar should only show a menu icon. Why are these elements merging and why isn't the sidebar showing up only on larger screens? The console logs indicate that the sidebar should appear, yet that's not the case.

Here's the code after a fresh reload, and here's how it looks after switching between mobile and desktop views (the expected outcome).

The mobile view functions correctly, and the desktop setup works fine after resizing the screen before reverting back to full size. However, the desktop display encounters issues on a fresh reload.

Answer №1

When the initial load is Server Side Rendered, useMediaQuery will be undefined, but it becomes defined when resizing the screen.
To resolve this issue, try loading your component with next/dynamic and setting SSR to false.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/hello3'),
  { ssr: false }
)

If you are concerned about SEO, consider improving UX by displaying a loader until determining whether it is desktop or not. Additionally, using CSS media queries might be a more suitable alternative to useMediaQuery.

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

Center the element in the header section

Utilizing angular material and css styling, I have successfully aligned the elements on my header page. However, I am facing a challenge in aligning the three icons (settings, help_outline, and person_outline) to the right side. <mat-toolbar color=" ...

Invoke the function declared within the $(document).ready() block

In an external JS file, I have: $(document).ready(function() { var example = function(){ alert("hello") } }); I am trying to find a way to call that function from my HTML. How can this be accomplished? <img src="..." ondblclick="example()" /> ...

paper-header-panel content div exhibiting unpredictable behavior

I am currently experimenting with Polymer 1.0 elements for a simple test. However, in the paper-header-panel test, it seems that the content area elements are either not visible or are overlapping with the paper-header div. You can view the demo here and ...

Words next to picture

Can someone help me with aligning different images of varying widths but the same height inline with text next to each image? I tried to do it, but it doesn't look good on responsive screens. Any suggestions on how to fix this? And if there's a b ...

Tips for reducing the amount of repetitive code in your reducers when working with redux and a plain old JavaScript object (

When it comes to writing reducers for Redux, I often encounter challenges. My struggle usually lies in wrapping a lot of my state manipulation in functions like .map and .slice. As the structure of my state object becomes more complex, the reducers become ...

A specialized React hook designed for fetching data in a continuous loop

Been struggling with this issue for hours :( I have a hook called useCollection which is designed to provide data retrieved from my API and updated in real-time using a websocket. It works perfectly for real-time updates, but I want it to also update the ...

An uncaught security error occurred when attempting to execute the 'pushState' function on the 'History' object

Here are the routes in my application: const routes:Routes =[ {path:'', component:WelcomeComponent}, {path:'profile', component: ProfileComponent}, {path:'addcourse', component: AddcourseComponent}, {path:'course ...

Transforming data in javascript

I am faced with a data transformation challenge involving extracting information from user input in Apache Superset using metrics. The data is assigned to the variable dataTransformation. {country: "Afghanistan", region: "South Asia", y ...

React: Encountered an unexpected error with the syntax. Unable to tokenize 'export'

My journey with React has just begun a few days ago, and everything was running smoothly until I deployed the project on production. Suddenly, the React build file started throwing this error: Uncaught SyntaxError: Unexpected token 'export' Up ...

Creating instances of a child class in Typescript using a static method in the parent class, passing arguments and accessing other static methods

Struggling with instantiating a child class from a static method in a base class. Looking to properly specify the return type instead of resorting to using any for all static methods. Tried a solution here, but it falls short when dealing with static metho ...

The search bar effortlessly slides into view on the navigation bar as I scroll down using Bootstrap 4

Is it possible to create a hidden searchbar within a navbar that only appears when scrolling down, and if so, can I set the timing for when it appears after scrolling? ...

In the thymeleaf fragment, the th:field attribute is marked with a crimson underline

I am facing an issue with a fragment that opens a modal when a button is clicked. Inside the modal, there is a form with a text field for token and submit button. However, I am getting a red squiggle underneath the th:field attribute "token", and I'm ...

Incorporate a PHP file from an external website, as plain text or HTML

My dilemma involves a php file that resides on a particular website (for example: ). This script generates html content, primarily consisting of text formatted with tags like <h2>, <p>, and so on. The task at hand is to take this text and embe ...

This seems off - NPM is downloading around 202M of modules, which doesn't seem accurate

Upon inspecting my package.json file, everything seems normal: { "name": "application_name", "version": "0.1.0", "private": true, "dependencies": { "bootstrap-toggle": "^2.2.2", "classnames": "^2.2.6", "html-react-parser": "^0.4.6", ...

TSLint is encountering the error code TS2459: The module "@azure/core-tracing" claims to have a local declaration of "Span" but does not export it, along with additional errors

I'm completely lost on how to tackle this error. The message I'm getting doesn't provide much insight, other than indicating an issue with the installation of '@azure/ai-text-analytics'. I've gone through the process of uninst ...

Describing the Significance of a Component Value within the Document Object

Every time I call a specific component in the DOM using its selector, I want to customize it by altering certain variables. This component will serve as a generic "Input Field" that I can define with unique values each time I use it. I specifically want t ...

span element failed to trigger onload event

I'm encountering a basic issue with my code as a beginner. Below is the HTML snippet: <!DOCTYPE html> <html> <head> <meta http-equiv='content-type' content='text/html; charset=utf8' /> <scrip ...

Can the hexadecimal value from an input type color be extracted and used to populate form fields that will then be displayed in a table after submission?

Hello everyone, I'm new to this platform and seeking guidance on how to improve my post! I recently created a CRUD app using Angular. It consists of a basic form with 4 fields, a color picker using input type='color', and a submit button. U ...

What are the steps to executing a function that instantiates an object?

Here is an object with filter values: const filters = ref<filterType>({ date: { value: '', }, user: { value: '', }, userId: { value: '', }, ... There is a data sending function that takes an obje ...

Prevent further scrolling on the slider by utilizing a link with the target ID in pure CSS

I've created a CSS slider, but I'm facing an issue where clicking the bullet and arrow navigation scrolls to the top of the slider from the extra space. Is there a way to prevent this behavior using only HTML and CSS? I've tried using a hre ...