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

Getting the value of "Page=?" from the href attribute in an HTML tag can be done using Selenium Webdriver and Java

I am looking to extract the value "page = ?" from a specific "href" tag in the HTML code below. I need this value for my Selenium WebDriver script so that my loop can iterate up to page 53. Can someone guide me on how to retrieve the "page =" value mentio ...

Navigate to a list item once Angular has finished rendering the element

I need to make sure the chat box automatically scrolls to the last message displayed. Here is how I am currently attempting this: akiRepair.controller("chatCtrl", ['$scope', function($scope){ ... var size = $scope.messages.length; var t ...

Troubles with showcasing user attributes in the view with ng-repeat and handle-bars in Angular.js

React.js, Express.js, MongoDB server.js: const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const routes = require('./routes/index'); const users = ...

Exploring the View-Model declaration in Knockout.js: Unveiling two distinct approaches

For my latest project, I am utilizing Knockout.js to create a dynamic client application with numerous knockout.js ViewModels. During development, I came across two distinct methods of creating these ViewModels. First method: function AppViewModel() { thi ...

Unable to render HTML through Jquery ajax functionality

success: function(json) { for (var i = 0; i < json.length; i++) { var response = json[i]; $('#rv-container').html('<p>' + response.name + '</p>' + '<span>' + response ...

Combining various functions into a single button

I am currently working on creating a full-screen menu that functions like a modal. Everything seems to be working fine, except for the fadeOut animation. Can someone please help me understand what is causing issues with my scripts/codes? I want the content ...

I'm having trouble with my code not working for get, set, and post requests. What could be causing this issue and how can I

Here are the TypeScript codes I've written to retrieve product details and delete them. import { Component, OnInit } from '@angular/core'; import {FormGroup,FormBuilder, FormControl, Validators} from "@angular/forms" // other impor ...

Using Rails' link_to method within Bootstrap modals

I'm trying to implement a voting system where users can vote on different items displayed in a Bootstrap modal. Each item is listed as a button on the index page, and when clicked, it opens up the modal for voting. However, I'm facing challenges ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...

Using PHP to access HTML content from a page that demands authentication

I need help developing a PHP script that can scrape data from an HTML page. Right now, it works perfectly with pages that don't require authentication. However, I'm struggling to figure out how to extract content from a page that requires users t ...

Bringing in a variable from a component that is dynamically imported

I have a dynamically imported (Map) component on my page. const Map = dynamic(() => import('../components/Mapcomp'), { ssr: false, }) In addition to the component, I also need to import a variable from it. const [taskImg, setTaskImg] = useS ...

The PHP page is not receiving the variable passed through AJAX

Within the following code snippet, there seems to be an issue with accessing the dataString variable in the comment.php page. To retrieve the variable name, I utilized $_POST['name']. $(document).ready(function(){ $("#submit").click( function() ...

You cannot utilize Lesson as a JSX Component in Next JS TypeScript

Below is my updated page.tsx code: import Aspects from '@/components/Aspects'; import FreeForm from '@/components/FreeForm'; import Lesson from '@/components/Lesson'; import React from 'react'; import { Route, Route ...

Having trouble with NextJs router 404 error when refreshing the page on Digital Ocean?

I am currently working with a NextJs project that has been exported as a static site and is being hosted on Digital Ocean's App platform. I am using next/router to handle routing within the application. One issue that I have encountered is when attem ...

position blocks next to each other within a container

Thank you for all the hard work! I've been struggling to figure out how to align blocks next to each other within a div. It may not be that difficult, but I just can't seem to find an elegant solution... Here is the HTML code snippet: <div ...

The PHP language includes a print language construct for outputting text

Having some trouble with a PHP script in my assignment related to page handling. When I submit it through another PHP page, it is showing the actual PHP code instead of executing properly, but it works fine when run standalone. I've created an HTML l ...

Tips for integrating v-virtual-scroll with v-table?

My Vuetify table is handling a large amount of data – 300 rows with 20 columns, some of which have calculated rowspans. To improve performance, I'm considering using the v-virtual-scroll component. I came across this sample code, which doesn't ...

Looking to utilize the <pre> tag without any external CSS styles defined in a separate stylesheet?

In my current project, I am using bootstreap v3.2. I am facing an issue where I need to display fetched content from the database on a page using the <pre></pre> tags. However, the problem is that the content is being displayed with the default ...

Is there a live password verification tool available?

Currently, I am conducting some initial research for my school's IT department as a student employee. The students at our institution are required to change their passwords every six months, but many of them struggle with the various password regulati ...

A guide on using Material UI - InputLabel in JavaScript

I'm currently integrating a form from this Codepen link into my project built with Codeigniter. However, I am encountering issues after incorporating material-ui into the CodeIgniter framework. The problems I am facing include an invalid token and an ...