Dominating React Components with Unique CSS Styles

Currently, I have developed a NavBar component.

I've implemented some JavaScript code that changes the navbar's background color once it reaches 50px. However, I am facing an issue in applying this scroll effect to only one specific file and not all files.

Specifically, I would like this scrolling effect to be active only on the homepage and not on any other pages such as aboutPage or others.

 const [sticky, setSticky] = useState(false);
 useEffect(() => {
   window.addEventListener("scroll", () => {
     window.scrollY > 50 ? setSticky(true) : setSticky(false);
   });
 }, []);
 
 return (
   <nav className={`container ${sticky ? "dark-nav" : ""}`}>
     <Link to="/">
       <img src={Logo} className="Logo" alt="" />
     </Link>
     <ul className={mobileMenu ? "" : "hide-mobile-menu"}>
       <li>
         <NavLink to="/">Home</NavLink>
       </li>
       <li>
         <NavLink to="/About">About</NavLink>
       </li>
       <li>
         <NavLink to="/Services">Services</NavLink>
       </li>
       <li>
         <NavLink to="/Contact">
           <btn className="btn">Contact Us</btn>
         </NavLink>
       </li>
     </ul>
     <img src={menuIcon} alt="" className="menu-icon" onClick={toggleMenu} />
   </nav>
 );

Answer №1

To ensure the scroll event listener is applied only to specific page URLs, you can add a check using window.location.pathname to extract the path without the domain.

useEffect(() => {
    const path = window.location.pathname.trim();
    if (path === "" || path === "/") { // checking for empty path or root path
        window.addEventListener("scroll", () => {
             window.scrollY > 50 ? setSticky(true) : setSticky(false);
        });
    }
}, []);

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

Videos fail to load on iPhone but load successfully on desktop and Android web browsers

I have been attempting to insert a video into my HTML page, but it's not working properly on my iPhone (I only see a crossed out play button). The video loads fine on desktop and Android devices. This issue isn't browser-related as I encounter th ...

Using Slick Slider and Bootstrap CSS to display text on top of images

Currently, I am utilizing the slick slider from and I want to overlay text on top of the image. I tried using bootstrap carousel-caption, which works well with any image. However, with slick slider, it seems like the text is not at the highest level as I ...

Encountering issues with calling a custom directive within another custom directive in AngularJS

I need to implement a custom directive within the template of another custom directive. Here are the code snippets for reference: Issue with Scenario 1 angular.module('myApp') .directive('customOnChange', function () { return { r ...

Utilize Next JS pages api to generate dynamic routes based on unique ids

In the content of my website, there is a collection of objects named stories that are displayed as an array. Additionally, I have a section where each individual story is showcased in detail. I intend to enable users to click on any story link within the ...

Form featuring a mandatory checkbox that must be selected in order to proceed; failure to do so will result in an

So here’s the situation: I have a form with a checkbox for agreeing to the terms of service, and I want to make sure it is checked before proceeding with the donation process. I only have the HTML code and no idea how to implement this functionality. Ide ...

How are "new" and "prototype.constructor" related in the realm of Javascript?

Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book: function Car() { var self = this; self.type = "Car" self.go = funct ...

Encountering a type error while trying to create a document within a nested collection in Firebase Firestore

While trying to submit the form with property data, I encountered an error message: FirebaseError: Expected type 'za', but it was: a custom Ha object. There doesn't seem to be any information available online explaining what a Ha object is o ...

Typescript error: Cannot access property "status" on type "never".ts(2339)

Currently, I have a method that utilizes nextjs/auth to sign in with credentials from a form. However, I am encountering a type checking error Object is possibly 'undefined'.ts(2532) const doStuff = async (values: any) => { const result: S ...

Using Vue.js, learn how to target a specific clicked component and update its state accordingly

One of the challenges I'm facing is with a dropdown component that is used multiple times on a single page. Each dropdown contains various options, allowing users to select more than one option at a time. The issue arises when the page refreshes afte ...

Easiest and quickest method to retrieve metadata from a website

Currently, I am using preg_match to extract the 'title' from websites, however, it is loading very slowly. Here is what I have so far: This code sends links to a function: <?php foreach($savedLinks as $s) { echo "<div class='sa ...

Is it possible that CSS files are not being excluded from content scripts in manifest.json?

I am looking to create a chrome extension that enforces a specific CSS style on all websites except for Gmail. However, I am facing an issue where the code in the content scripts section of the manifest.json file is not working as expected. Even though I h ...

React Project Initialization Error: Module Not Located | webpack-dev-server Issue

Lately, I've been consistently facing a 'Module not found' error every time I execute npm start or yarn start on my local machine. Interestingly, this error only pops up when I create a new project locally; projects cloned from GitHub work w ...

Resize the main container to fit the floated elements

I've been working on constructing a family tree, and the last part of the functionality is proving to be quite challenging for me. My family tree consists of list elements that are all floated to the left. Currently, when the tree expands beyond the ...

Is your YQL JSON script failing to provide the expected output?

Here is a script that I have copied almost directly from this. Why is it that the code below does not seem to return anything? ajax.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html dir="lt ...

Ensure that the content inside the centrally aligned div is also aligned at the

Looking for a way to center a box on a website I'm designing? Instead of aligning it based on existing centering, use the following HTML / CSS code to ensure that the white box is perfectly centered on the page. .loading { position: fixed; z-in ...

Adjust the source of the HTML5 video tag based on the orientation of an iPad

I am currently coding an HTML5 page specifically for iPad Mobile Safari, which includes a video tag for embedding video files. I have successfully implemented CSS3 media queries to determine the orientation of the iPad. My next challenge is to dynamically ...

Dynamic Search Functionality using Ajax and JavaScript

function fetchData(str) { if (str.length == 0) { var target = document.querySelectorAll("#delete"); return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && ...

Showing JSON information in an Angular application

Upon page load, I am encountering an issue with retrieving and storing JSON data objects in Angular scope for use on my page and in my controller. When attempting to access the value, I receive the error message: angular.js:11655 ReferenceError: data is ...

Calculating and displaying the output on an HTML page: A step-by-step guide

Within my HTML, I have two values stored in Session Storage: "Money" and "Time". These values are based on what the user inputted on a previous page. For example, if someone entered that they need to pay $100 in 2 days. My goal is to generate a list that ...

How to extract a JavaScript object from an array using a specific field

When dealing with an array of objects, my goal is to choose the object that has the highest value in one of its fields. I understand how to select the value itself: Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; })) ... but I am unsur ...