React Application not reflecting recent modifications made to class

My current project involves creating a transparent navigation bar that changes its background and text color as the user scrolls. Utilizing TailwindCSS for styling in my React application, I have successfully implemented the functionality.

// src/components/Navbar.js
import React, { useState } from 'react';

const Navbar = () => {
  const [navbarBackground, setNavbarBackground] = useState('transparent');
  const [navbarTextColor, setNavbarTextColor] = useState('slate-200');

  const handleScroll = () => {
    const scrolled = window.scrollY;
    if (scrolled > 20) {
      setNavbarBackground('slate-200');
      setNavbarTextColor('slate-800');
    } else {
      setNavbarBackground('transparent');
      setNavbarTextColor('slate-200');
    }
  };

  window.addEventListener('scroll', handleScroll);

  return (
    <nav 
      className={`flex justify-between p-4 fixed top-0 w-full z-50 transition bg-${navbarBackground}`}
    >
      <div className={`font-cursive text-${navbarTextColor}`}>Luca Cangelosi</div>
      <div className="flex space-x-10">
        <a className={`text-${navbarTextColor} font-semibold transition cursor-pointer`}>About</a>
        <a className={`text-${navbarTextColor} font-semibold transition cursor-pointer`}>Store</a>
        <a className={`text-${navbarTextColor} font-semibold transition cursor-pointer`}>Contact</a>

        <div>
          <i className={`text-${navbarTextColor} fas fa-shopping-cart transition cursor-pointer`}></i>
        </div>
      </div>
    </nav>
  );
};

export default Navbar;

The code functions by checking the vertical position of the scroll. If the position is at the top of the page (Y-position 0), the navbar has a class of bg-transparent with link text color set to text-slate-200. Otherwise, the navbar background becomes bg-slate-200, while link colors change to text-slate-800.

However, upon initial running of npm start, the code does not behave as expected. The navigation bar remains transparent even after scrolling down, and link colors are uncertain. Interestingly, fixing one link color explicitly seems to resolve this issue temporarily until reverting back.

Why does this erratic behavior occur initially? What measures can be taken to ensure proper functioning from the start, especially in production?

Any insights or solutions would be greatly appreciated. Thank you!

Answer №1

In my opinion, using boolean for the state value can enhance readability.

const [isNavbarBackground, setIsNavbarBackground] = useState(false);
const [isNavbarTextColor, setIsNavbarTextColor] = useState(false);

Avoid adding event listeners directly in the component body as it may result in multiple listener additions.

Placing addEventListener inside useEffect ensures that the listener is only added once.

useEffect(() => {
    const handleScroll = () => {
      const scrolled = window.scrollY;
      if (scrolled > 20) {
        setIsNavbarBackground(true);
        setIsNavbarTextColor(true);
      } else {
        setIsNavbarBackground(false);
        setIsNavbarTextColor(false);
      }
    };
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

To toggle the class name dynamically, you can use this approach.

className={`flex justify-between p-4 fixed top-0 w-full z-50 transition ${isNavbarBackground ? 'bg-slate-200' : 'bg-transparent'}`}

Answer №2

Make sure to include your complete class name within the useState hook.

slate-400

text-slate-400 Or bg-slate-400

If you use slate-400, tailwindcss will not generate the appropriate classNames for your component as it is not supported by tailwindcss (as per the Docs).

Your revised code should look like this:

import { useState, useEffect } from 'react';

const Navbar = () => {
  useEffect(() => {
    window.addEventListener('scroll', () => {
      if (window.scrollY > 20) {
        setNavbarBackground('bg-slate-200');
        setNavbarTextColor('text-slate-800');
      } else {
  ...
export { Navbar };

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

running a prompt command from my PHP/HTML script

I currently run a puppeteer program by typing c:\myProgram>node index.js in the command prompt. However, I would like to automate this process through my PHP program instead of manually entering it each time. Something similar to this pseudo-code ...

Can you guide me on setting up a multi-selection option for a field in my Wordpress Theme by Templatic?

My website is http://aisiel.ro, a real estate agency website. Under the slider, there is a search field where we have the option to select an area called "Zona" - Area in English. Currently, users can only choose one area for their search, but I want to ...

Header text aligned with image to accommodate parent size

Having trouble aligning an image/logo next to my header text while maintaining its aspect ratio and fitting within the container size. The goal is to have both the text and image horizontally centered. The parent div cannot have a fixed height as it needs ...

"Is it possible to include a query in a reducer with

Hey, how can I implement this inside a reducer to modify the state's value? doc = { id:"zf123ada123ad", name:"examp", subdoc:{ name:"subdoc examp", subsubdoc:[{ id:"zcgsdf123zaar21", subsubsubdoc:[{ ...

Ways to align content in the center using Vuetify3

I have a component positioned at the top of the page, but I would like it to be centered instead. https://i.sstatic.net/wSFBP.png Something like this: https://i.sstatic.net/rfqAB.png Here is my current code: <template> <v-container class=" ...

Building Individual Elements in Angular 2

My task involves creating two distinct components in Angular 2, the Users component and the Clients component. These components are not nested and do not have any relationship. To call these components separately, I typically use main.ts as the main entry ...

Creating HTML tables with consistent vertical lines and broken horizontal lines

Looking to style an HTML table with unique grid-lines. Wanting continuous horizontal lines (foreground) and interrupted vertical lines (background), overlaid by the horizontal lines. Different line heights, some 1px, others 2px for variety. Vertical lines/ ...

The Challenge with jQuery Nano Scroll

I recently added the jQuery Nano Scroll plugin to my HTML page. However, I am facing an issue where the scrollpane is not visible. When I inspect the div using Chrome, the scrollpane appears. Any suggestions on how to resolve this? Here's a snippet ...

URL validation RegEx in AngularJs using Javascript

I am looking for the following URLs to return as true other.some.url some.url some.url/page/1 The following URL should be flagged as false somerandomvalue Here is the regex I have been experimenting with so far: /^(?:http(s)?:\/\/) ...

I possess an array of objects that includes both images and documents. My goal is to examine the mime_type of each object and select the first element in React to be displayed within an <img> tag

I have an array of objects that contain images and documents. My goal is to display the first image only if the mime_type is 'image/jpeg' or 'image/png'. I am working with React. Despite my attempts, I keep encountering undefined resul ...

The z-index property does not seem to apply to pseudo elements

I am facing an issue while trying to add a pseudo element after a div in my react project. Surprisingly, the code works perfectly fine in CodePen but fails to work on my local machine. I have applied z-index only in CodePen, which seems to resolve the issu ...

Turn off pagination for tables in Material-UI

Currently, I am utilizing the TablePagination component from Material-UI in my React project. Unfortunately, this component does not come with a built-in disabled prop. I do have a boolean variable called loading that I would like to utilize as a paramet ...

Align an Svg layer within another Svg to the center

I'm attempting a seemingly easy task: placing one svg layer inside another and centering it. In this particular situation, I have a simple arrow (represented by an svg path) that needs to be nested within a rectangle (a square shape in this case). T ...

Inserting a large number of records in MySQL using a batch insertion method

Currently, I am facing an issue with inserting multiple records into a MySQL table at once. Just so you know, I am using Node.js along with MySQL (you can find more information about it here: https://www.npmjs.com/package/mysql) Here is what I have been ...

What could be causing my table to malfunction in IE8?

Is it just me, or do my CSS tables not work on IE8? <div class="main-table"> <div class="row"> <a class="secondary-table" href="#"> <div class="secondary-row"> <div class="secondary-cell"> ...

Is there a restriction on the number of stylesheets per page in Internet Explorer 8?

Discussing the limitations of CSS in a forum thread, a user shared insights: A user mentioned that Internet Explorer has is known to have a restriction of 4096 CSS rules per file. For more information, check out this source. Additionally, there might be ...

Stop the color buffer from being automatically cleared in WebGL

Removing gl.clearColor(c[0],c[1],c[2],1.0); gl.clear(gl.COLOR_BUFFER_BIT ); does not stop the screen from getting cleared at the start of the next draw cycle. Is there a method to avoid this situation? I am aiming for an overpaint effect. ...

Acquire the value of ant-design Select dropdown upon hover

How can we detect the selected option in an ant-design dropdown when it is hovered? <Select defaultValue="lucy" style={{ width: 120 }} onChange={handleChange}> <Option value="jack">Jack</Option> <Option value=& ...

Achieve a fade-in effect on an element with TailwindCSS when clicked

Currently working on an app and facing a challenge with fading the menu in and out when clicking a button. The menu is rendering on click using state, but struggling to achieve the fade in / fade out effect. Interestingly, when tweaking the opacity value d ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...