Is there a way to ensure that Tailwind CSS loads before rendering components in NextJS?

While developing my web application, I encountered an issue with the tailwind CSS styling. The styles seem to load correctly, but there is a slight delay before they take effect. This results in users seeing the unstyled version of the website briefly before the tailwind CSS classes kick in and apply the styles.

I'm puzzled as to why this happens since the project configurations are mostly default, set up using create-next-app, with only minor changes like adjusting the tsx settings (specifically changing moduleResolution from "bundler" to "node"). Even reverting back to "bundler" didn't resolve the issue.

In my tailwind.config.js:

import type { Config } from 'tailwindcss'

const config: Config = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    './app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      backgroundImage: {
        'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',
        'gradient-conic':
          'conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))',
      },
    },
  },
  plugins: [],
}
export default config

In my tsconfig.json:

{
  "compilerOptions": {
    // compiler options here...
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

In my layout.tsx:

// code here...

In my Navbar.tsx:

// code here...

In my globals.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

I've researched this issue and came across a thread discussing similar problems, but none of the proposed solutions have worked for me. Any assistance on resolving this would be greatly appreciated. Thank you!

Answer №1

Sharing this in case others are facing a similar issue.

If you're encountering the same issue as me and using MUI, that could be causing the problem.

The root of the issue is not tailwind itself. I discovered that the conflict arose from using MUI alongside tailwind. Due to MUI's own styling engine, it clashed with the tailwind classes I was applying.

MUI provides instructions on resolving this, but my attempts were unsuccessful. I'm not certain why, but I'll update this response if I find a solution.

I recommend starting by following MUI's guidelines for styling compatibility.

If that doesn't work, it might be best to remove MUI components and utilize html + tailwind instead.

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

Next.js 13: Dealing with the "Objects are not valid as a React child" error while using async/await to retrieve data

Currently, I am working on a project using Next.js 13 and the new app directory structure. One of my tasks involves fetching data from an API. However, every time I attempt to do this with async/await, I encounter an error message stating: "Objects are not ...

Angular: Array in the template re-renders even if its length remains unchanged

Below is the template of a parent component: <ng-container *ngFor="let set of timeSet; index as i"> <time-shift-input *ngIf="enabled" [ngClass]="{ 'mini-times' : miniTimes, 'field field-last&ap ...

Are all components in Next.js considered client components by default?

I have created a Next.js app using the app folder and integrated the Next Auth library. To ensure that each page has access to the session, I decided to wrap the entire application in a SessionProvider. However, this led to the necessity of adding the &apo ...

Having trouble achieving success with browser.addcommand() in webdriverIO using typescript

I tried implementing custom commands in TypeScript based on the WebdriverIO documentation, but unfortunately, I wasn't able to get it working. my ts.confg { "compilerOptions": { "baseUrl": ".", "paths": { "*": [ "./*" ], ...

Struggling to identify the error while utilizing Jasmine's throwError function

I am relatively new to using Jasmine and have been experimenting with the toThrowError() function. However, I can't seem to get my test to pass successfully. In one of my functions, I purposely throw an error: test.service.ts test(list:{}){ if ...

TypeScript and Express create a powerful array combination capability within the type system

After defining the EventType as either "TYPE A" or "TYPE B", I am looking to create a type for an array that can only contain one or both of these event types. Simply typing it as an EventType[] allows duplicates, which is not ideal. type Test = EventType ...

Iterating through elements within the ng-content directive in Angular using *ngFor

Is it possible to iterate through specific elements in ng-content and assign a different CSS class to each element? Currently, I am passing a parameter to enumerate child elements, but I would like to achieve this without using numbers. Here is an example ...

The type 'GetServerSidePropsContext<ParsedUrlQuery, PreviewData>' does not include property X

My current setup includes: type Session = { bearer: string, firstName: string, lastName: string, etc... }; interface ServerContext extends GetServerSidePropsContext { session: Session, }; export type ServerProps<P extends { [key: string]: ...

Impact when returning a React.FC Component

Using React, I have encountered a challenge with my site: I have a function that generates a Card component displaying information about my store's products (#1). To display this on the screen, I map through the array returned by the backend and pass ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

execution of synchronized task does not finish

My approach to running Protractor tests in a headless mode using Xvfb may not be the most efficient, so let me outline my high-level requirement first. I am utilizing the angular2-seed and I aim to execute Protractor tests in a headless mode by incorporat ...

Oops! Looks like there was an error trying to assign the value "$event" to the template variable "element". Remember, template variables can only be read

Can anyone assist me in identifying the issue with this code? <div *ngFor="let element of list; let index=index"> <mat-form-field> <input matInput type="string" [(ngModel)]="element" name="element ...

ngModelChange doesn't trigger if the value is manually altered

Here is the scenario I am experiencing: //html <input (ngModelChange)="onSelection()" [(ngModel)]="selectedNode" > // in the ts file onSelection() { alert('changed'); } Typing something inside the input tri ...

Can you use TypeScript to define generic React functional components?

I am looking to add annotations to a generic in a React functional component like the following: import React, {useEffect, useState} from "react"; interface PaginatedTableProps{ dataFetcher: (pageNumber: number) => Promise<any>, columnNames: ...

Difficulty locating the module in Typescript/Javascript

Currently facing an issue while trying to incorporate a module called "request" into my Angular 2 Typescript project from here. Despite following the usual installation process with npm install --save request and also attempting typings install request -- ...

Error: LocalStorage could not be located in Next.js

I'm a beginner in Next.js and I am facing an issue with unauthorized requests while trying to inject data from my API. Everything seems to be working fine except for some requests that are still returning as unauthorized. In order to access my API, I ...

There is an issue with the Next.js middleware: [Error: The edge runtime is not compatible with the Node.js 'crypto' module]

Struggling with a problem in next.js and typescript for the past 4 days. If anyone can provide some insight or help with a solution, it would be greatly appreciated. Thank you! -- This is my middleware.ts import jwt from "jsonwebtoken"; import { ...

List the hours using TypeScript

My data table is displaying records including a column for hours spent and a row showing the total sum of those hours. While the hours are being added correctly, the minutes display as NaN, such as 52:Nan. Can someone assist me in resolving this issue? co ...

What is the best way to send multiple parameters to @Directives or @Components in Angular using TypeScript?

I am facing some confusion after creating @Directive as SelectableDirective. Specifically, I am unclear on how to pass multiple values to the custom directive. Despite my extensive search efforts, I have been unable to find a suitable solution using Angula ...

Hierarchy-based state forwarding within React components

As I embark on the journey of learning Typescript+React in a professional environment, transitioning from working with technologies like CoffeeScript, Backbone, and Marionettejs, a question arises regarding the best approach to managing hierarchical views ...