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

Using Flexbox for laying out content in both columns and rows

Hey there, I'm looking for a little help. It's been quite some time since I last built a website from scratch and I want to keep things simple this time around. I've used breakpoints before, but I'm curious if Flexbox could be a better ...

What is the method for utilizing a filter to extract the specific value from the elements within an array of double objects?

I am facing an issue with my code where I have an array called pick containing objects and another object named diaryItem. My goal is to extract only the object with the name 'wormColor' from the diaryItem object. Unfortunately, when I tried run ...

What is the best way to horizontally align divs with CSS?

I have been using a combination of table and CSS to center divs on my page. Here is the code I'm currently using: <table width="69" border="0" align="center"> <tr> <td width="59"> <div style="position:relative;"> ...

Customize settings for individual nested dynamic routes in Next.js

My web app is created using Next.js and TypeScript. It has the capability to display a multitude of nested paths, such as: /groups/sports/team-sports/football educations/elementary/class/group/pre-school/kids /members/senior-high-school/teachers/mathemati ...

I'm looking to customize the React Material UI responsive drawer by removing the padding from the Toolbar

If I have the code found here: https://stackblitz.com/edit/react-nqkupy?file=demo.tsx which is based on the "Responsive drawer" section in the material UI documentation: https://mui.com/material-ui/react-drawer/#responsive-drawer but I customized it by ...

The index "is_ajax" has not been defined

I attempted to create a simple login functionality using Ajax. Following a tutorial that didn't use classes and functions in PHP, I tried restructuring the code with classes and functions. However, I encountered the error: Undefined index: is_ajax He ...

What is the best way to continuously run a series of functions in a loop to create a vertical news ticker effect?

I'm in the process of creating a vertical latest news ticker, and although I'm new to javascript, I'm eager to learn and build it myself. So far, I've come up with this, but I want the news cycle to restart once it reaches the end. ...

`Monitoring and adjusting page view during window resizing in a dynamic website`

Situation: Imagine we are reading content on a responsive page and decide to resize the browser window. As the window narrows, the content above extends down, making the entire page longer. This results in whatever content we were previously viewing bein ...

A straightforward jQuery conditional statement for dynamically generated content

If the div '#ajax' contains content, I want to make the div '.container' clickable. Here is the basic jQuery script I have implemented: if ('#ajax:empty') { $('.container').css('pointer-events', ' ...

Submitting values using the serialize method and Ajax involves sending placeholders

Looking for a solution: <form class="pure-form pure-form-stacked" method="post" enctype="multipart/form-data"> <input type="text" name="name" class="button-size-1" placeholder="*Name"> <input type="text" name="email" class="but ...

Utilizing Radio Buttons for Table Selection in a React Application

Currently, I am utilizing React, MUI, and Formik in my project. My task involves implementing a table where only one radio button can be selected per row. How can I achieve this functionality? If you want to take a look at my code, it's available on ...

The conundrum of jsPDF's image compatibility

I am attempting to generate a PDF document on the client-side using the jsPDF library. The code I have written is as follows: <script type="text/javascript" src="libs/base64.js"></script> <script type="text/javascript" src="libs/sprintf.js" ...

Displaying a message when there are no results in Vue.js using transition-group and encountering the error message "children must be keyed

Utilizing vue.js, I crafted a small data filter tool that boasts sleek transitions for added flair. However, I encountered an issue with displaying a message when there are no results matching the current filters. Here's what I attempted: <transit ...

Encountering a connectivity problem with cx_oracle in a Flask application

Currently, I am in the process of creating an application that allows users to input data from an Excel spreadsheet and then upload that information to a database based on whether they select option A or option B. The problem I am encountering is that aft ...

Determining height of an element in AngularJS directive prior to rendering the view

As I dive into the world of Angular, any assistance is greatly welcomed. My goal is to vertically align a div based on screen size (excluding the header and footer) when the page loads, the window resizes, and during a custom event triggered by the user ex ...

How can you retrieve input values from a form using a button click but without requiring a

I am facing an issue with the delete button on my form. The form has three buttons - one to edit the form on another page, one to add a value on the existing page, and one to delete a value. While the submit and edit buttons work fine, I am struggling wi ...

Troubleshooting the issue with default useAsDefault routing in Angular 2

I have implemented Angular 2 for routing and Node for local hosting. However, I encountered an issue where using 'useAsDefault:true' for my route caused the nav bar links to stop functioning properly. The URL would redirect to http://localhost/ ...

Implement a custom placeholder feature for InputNumber in Blazor

I have a question about adding a placeholder to the InputNumber component. I attempted the following code but unfortunately, it did not work as expected. //Code behind public int? Hour { get; set; } //razor page <EditForm Model=&quo ...

Error Message: The specified HTML element already contains two instances of the WebViewer, leading to a conflict in PDFTron React TypeScript Next

Having some trouble using pdftron with my docx editor. I can use the editor fine, but keep encountering an error like the one shown below: https://i.stack.imgur.com/OnJxE.png https://i.stack.imgur.com/l9Oxt.png Here is a snippet of my code: wordeditor.t ...

Determine the week number based on a specified starting day for the week

If I have a custom week start day other than Monday, how should the getWeekNumber() prototype for the Date class be modified? Here is the existing code for calculating the ISO Week Number: Date.prototype.getWeekNumber = function() { // Create a dupli ...