Using Next.js and Tailwind CSS to apply a consistent pseudo-random color class both on the server and client side

I am faced with a challenge on my website where I need to implement different background colors for various components throughout the site. The website is generated statically using Next.js and styled using Tailwind.

Simply selecting a color using Math.random() is not a viable solution, as it may result in different colors between the client and server, causing the color to change rapidly upon initial render.

const backgroundColors = ["beige", "purple", "orange"];
const shuffledBackgroundColors = backgroundColors.sort(
  () => Math.random() - 0.5
);

This approach leads to an error:

Warning: Prop className did not match. Server: "bg-purple" Client: "bg-orange"


To address this issue, I considered using a pseudo-random number generator where I could control the seed to ensure consistency between the server and client:

import gen from "rand-seed";

const r = new gen(new Date().getUTCMinutes().toString());
const backgroundColors = ["beige", "purple", "orange"];
const shuffledBackgroundColors = backgroundColors.sort(() => r.next() - 0.5);

While this method seemed effective on localhost, deploying it to Vercel revealed discrepancies between the server and browser, resulting in undesirable outcomes.

Ultimately, the goal is to have a reliable way to select a new random color on each page load, rather than just once per minute.

Is there a more dependable approach to achieve this?

Answer №1

To generate a seed in Next.js, you can use server-side code and pass it to the React side by utilizing functions like getStaticProps (or getServerSideProps for dynamic pages).

export async function getStaticProps(context) {
  return {
    props: {
      seed: new Date().getUTCMinutes().toString()
    },
  }
}

The generated props.seed will be accessible within your page component on both the server and client sides.

If you need different behavior on page refresh, consider using getServerSideProps. Alternatively, you can use the revalidate parameter with getStaticProps to periodically update the props.

If you only require one color (or an array of colors), you may skip generating a seed altogether and perform the necessary operations directly on the server side:

export async function getStaticProps(context) {
  return {
    props: {
      colors: ["beige", "purple", "orange"].sort(() => r.next() - 0.5)
    },
  }
}

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

Creating a method to emphasize specific words within a sentence using a custom list of terms

Looking for a way to highlight specific words in a sentence using TypeScript? We've got you covered! For example: sentence : "song nam person" words : ["song", "nam", "p"] We can achieve this by creating a custom pipe in typescript: song name p ...

A guide on implementing JSON data projection with TypeScript

{ "ClaimType": ["The 'Claim Type' should have a minimum length of 4 characters. You have only entered 2 characters."], "ClaimValue": ["The 'Claim Value' should have a minimum length of 4 characters. You have only entered 1 chara ...

state inside react-query useQuery hook resetting to default state when window is focused

After the initial build, my code works flawlessly. Here's a snippet: const [conditionState, setConditionState] = useState([]) const { data: solicitud, error } = useQuery(['SOLICITUD', _id], async () => { const { data } = await axios ...

How to eliminate Image notifications in NextJS

I keep receiving a warning about the local images on my website: Image with src "http://localhost:3000/_next/static/media/icon_home.0f967506.svg" has either width or height modified, but not the other. If you use CSS to change the size of your image, also ...

Debouncing functionality within a functional component

I am currently working on implementing debounce in a functional component: import React, { useCallback, useState } from 'react'; import debounce from 'lodash.debounce'; function Tags() { const [value, setValue] = useState('' ...

Error encountered in Next.js app: Unable to listen due to permission denied on IP address 0.0.0.0 and port 80

Encountering an error when attempting to run a Next.js app on port 80. Below is my package.json configuration: "scripts": { "dev": "next dev -p 80", } The following error occurs when running yarn dev: Error - Failed to s ...

Select numerous files and conveniently delete them using the angular delete button

Background: In one of my tables, there is a column where users can either choose or upload files as input. I have implemented a feature that allows users to select multiple files at once. Issue at Hand: What I am trying to achieve is to have an 'x&ap ...

Updates to the Tailwind file are not appearing on the page after reopening the file

Every time I reopen the project, the file tailwind properties do not get rebuilt and if I add new properties like text-color, they are also not reflected. Any suggestions on how to solve this issue? I need the project to update and take in new properties ...

Unable to locate properties "offsetHeight" or "clientHeight" within a React/Next.js project developed in TypeScript

I have a unique customized collapsible FAQ feature that adjusts its height based on whether it's expanded or collapsed. import { useState, useRef, useEffect } from "react"; export default FAQItem({title, description}: FAQItemProps) { cons ...

JavaScript: specify parameters for function inputs

I'm curious about optimizing Javascript/Typescript functions arguments for clean code. To demonstrate, let's consider a basic example. Imagine I have a React component with a view property as props: <Grid view="Horizontal" /> ty ...

The error message "ng: command not found" popped up despite successfully installing the latest @angular/cli using npm linking

Here is the information about my current setup: Node version: v10.15.3 NPM version: 6.4.1 I attempted to run the following command: Command: npm i -g angular/cli An error occurred while executing: npm ERR! /usr/local/bin/git ls-remote -h -t ssh:// ...

What is the reason for a class's attributes being considered undefined even after they have been previously set?

Within my code, there is a class called WorkspaceDatabase that stems from the Dynamic Tree Example. I have incorporated some debugging information to gain a clearer understanding of the issue at hand. The Issue: Upon entering the complete() function, an ...

Next.js requires specifying explicit dimensions for local images

After reviewing their documentation, I discovered that when using a local image (e.g. from the public/ folder), specifying the width and height of an image is not necessary. Here is an example of how my setup is configured: import Image from 'next/Ima ...

Best practice for encapsulating property expressions in Angular templates

Repeating expression In my Angular 6 component template, I have the a && (b || c) expression repeated 3 times. I am looking for a way to abstract it instead of duplicating the code. parent.component.html <component [prop1]="1" [prop2]="a ...

What is the best way to send additional variables to my npm script?

Currently, I am integrating typeorm with nextjs. Unfortunately, running manual migrations seems to be quite complex. Initially, I have set up the following npm script: "typeorm": "ts-node -P cli-tsconfig.json -r tsconfig-paths/register ./nod ...

Employing the filter or find technique to extract an element contained within a JSON data structure

Is it possible to retrieve one of these items using the filter or find method to search for a match within the fiberAgrupations array? I attempted the following: const landlineRate = this.monolineJsonRates[0].cambioCaudal.getAll() .filter(landlinedRat ...

Steps to assign a JSON file to an array within an object in Angular

What is the best way to assign a JSON file to an array within my "Client" object? I currently have a JSON file named Clients.json with the following structure: { "clients": [ { "firstName": "nameA", "lastName": "lastA", "doctorsNam ...

Change a Typescript class into a string representation, utilizing getter and setter methods in place of private variables

Below is a snippet of TypeScript code: class Example { private _id: number; private _name: string; constructor(id: number, name: string) { this._id = id; this._name = name; } public get id(): number { return t ...

The conditional type in TypeScript is malfunctioning

Upon finishing an article discussing conditional types in TypeScript located at: I have attempted to implement a conditional type in the following function: function convertToIsoString<T extends number|undefined>( timestamp:T ): T extends number ...

Trouble with maps not showing up and the console isn't showing any errors when using @react-google-m

Currently, I am facing an issue while trying to integrate Google Maps by following a blog post that provides instructions on next13 TypeScript. Despite reaching the point where the maps should be displayed, nothing appears on the screen. Surprisingly, ther ...