Encountering a scrolling glitch in React: while it functioned properly using only HTML, CSS, and JS, the issue persists when implemented

Encountered a strange minor bug while working on my project. The issue is related to the functionality of clicking on the .nav li element to close the navbar. Surprisingly, this behavior works flawlessly when implemented in pure HTML, CSS, and JS, but fails to operate as expected in a React environment. Below is the React code snippet:

import React from 'react';
import Nav from './javascripts/Navigation';
import Ham from './javascripts/Hamburger';
import { Link } from 'react-scroll';
import '../styles/Navbar.scss';

const Navbar = () => {
    React.useEffect(() => {
        Nav();
        Ham();
    }, []);
    return (
        <nav className="nav-container">
                <ul className="nav">
                    <div id="nav-icon">
                        <span></span>
                        <span></span>
                        <span></span>
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                    <li>
                        <Link
                            to="container"
                            smooth={true}
                            duration={500}
                            offset={-107}
                        >
                            Home
                        </Link>
                    </li>
                    <li>
                        <Link
                            to="abt-container"
                            smooth={true}
                            duration={500}
                            offset={-107}
                        >
                            About
                        </Link>
                    </li>
                </ul>
        </nav>
    );
};
export default Navbar;

SCSS

$w: #fff;
%nav {
    position: sticky;
    display: flex;
    padding: 15px 30px;
}
...

jQuery

import $ from 'jquery';

const Hamburger = () => {
    let isOpen;
    ...
}
export default Hamburger;

Experimented with a different approach which functioned correctly outside of React, yet failed within a React setup despite similar implementations.

let isOpen;
    $(document).on("click", "#nav-icon", function () {
        ...
    });
...
.nav-container .nav, .nav-container {
  ...
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="nav-container">
                <ul class="nav">
                    ...
                </ul>
        </nav>

Answer №1

the issue is not with React, but rather lies in how the "Link" component is implemented. The "Link" component stops event propagation when handling a click event, which can prevent your handler from being triggered.

To solve this problem, you can pass your own click handler to the "Link" component by using the "onClick" property. This click handler can be written using jQuery, allowing you to reuse existing code.

Here is what you need to do:

  1. Move your current jQuery click handler into a separate function

import $ from "jquery";

export function closeNavbar() {
 $("#nav-icon").removeClass("open");
 $(".nav").css({ padding: "15px 30px" });
 $("#nav-icon").css({ paddingBottom: "0" });
 $("li").css({ display: "none" });
}
  1. Pass this function as the "onClick" property to the "Link" component
    <nav className="nav-container">
      <ul className="nav">
        <div id="nav-icon">
          ...
        </div>
        <li>
          <Link
            onClick={() => closeNavbar()}
            ...
          >
            Home
          </Link>
        </li>
      </ul>
    </nav>

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

Can anyone explain to me how to render attributes of a tag in Vue? I'm curious about how v-for interacts with HTML

<ul> <span class="tabs" :class="{ activeTab: selectedTab === tab }" v-for="(tab, index) in tabs" @click="selectedTab = tab" :key="tab"> {{ in ...

Create a filled Material UI icon symbol

For my React app utilizing the Material UI library, I have incorporated Icons as symbolic representations. By including the baseClassName: 'material-symbols-rounded' in all icons through the global theme.js file: MuiIcon: { defaultProps: { baseCl ...

jQuery class does not apply correctly in IE9

Currently, I'm designing a menu for a WordPress theme and facing a styling issue. I aim to differentiate between menu items with submenus and those without by applying different styles on hover. Here's the jQuery code snippet I am using: $(docum ...

Issue with adding HTML content to bootstrap modal not functioning as expected

Having trouble displaying an image in a bootstrap modal by using data- attribute within a php foreach loop. The image doesn't seem to appear in the target div. Here's my code snippet: <script> $(document).ready(function(){ $( ".subscri ...

Disable the click event using jQuery

$("button").click(function (){ $("<button>Start</button>).appendTo('main'); }); The code above introduces a functionality where clicking a button generates another button dynamically. However, each subsequent click kee ...

AngularJS: Utilizing angular-filter for grouping by two columns

I may come across as a bit confusing, so please allow me to clarify. Note: An operational piece of code (POC) has been included with this post. I have an array of objects with 3 properties: name name team team_rank $scope.players = [ {name: & ...

Creating dynamic form fields using AngularJS

I have a form that includes an input field, a checkbox, and two buttons - one for adding a new field and one for deleting a field. I want to remove the add button and instead show the next field when the checkbox is checked. How can I achieve this? angu ...

Discover an Effective Approach for Transmitting Form-Data as a JSON Object

Hey there! I'm encountering a bit of an issue with sending some data as a JSON object. The problem arises when trying to send images using FormData. It seems like I need to convert my form data into a single JSON object. Can anyone assist me with this ...

A Bluebird promise was generated within a NodeJS handler function, however it was not properly returned from the function

Below is the nodejs code for an express middleware function: Middleware.is_authenticated = function(req, res, next) { if(req.system_session == undefined || req.system_session.login_status == false) return res.status(401).send({errors: true, error: &ap ...

Attempting to designate a comment as private or public by utilizing a checkbox. Employing AJAX to send data to PHP and store it in a MySQL

Currently, the checkbox is returning an [objectO instead of a simple YES or NO value. Currently, my checkbox field is set up as a VARCHAR with a length of 3, but I'm wondering if I should be using TINYINT or Boolean instead. If so, what changes do I n ...

ASP.NET is failing to receive Request.Files, returning null instead

I am attempting to upload an Excel file using XMLHttpRequest and FormData in ASP.NET, but I keep encountering the issue of Request.Files being null in ASP.NET. Below is the code I am using - can someone please assist me with this? function BulkUploadUse ...

Is there a way to create a div that resembles a box similar to the one shown in the

Hello, I am attempting to achieve a specific effect on my webpage. When the page loads, I would like a popup to appear at the center of the screen. To accomplish this, I have created a div element and initially set its display property to 'none'. ...

Using the jQuery attr method to assign values to newly created DOM elements generated by an AJAX request

I have a div on a webpage that undergoes changes through AJAX requests triggered by user interaction with a dropdown menu. When the page first loads, I have a script to disable autocomplete for all text input elements: //Prevent browser autocomplete funct ...

Endlessly refreshing occurs when attempting to load a separate CSS stylesheet using document.write

I am attempting to implement two separate stylesheets on my WordPress blog - one for web access and another for our iOS app. Currently, we are adding ?app=true to the URL when accessing content through the app in order to distinguish between the two. Using ...

Is there a way to access the value of a variable within a loop inside a function and store it in a global variable?

I am struggling to retrieve the value of a variable after it has passed through a loop. I attempted to make it a global variable, but its value remains unchanged. Is there any way to achieve this? Below is my code snippet where I am attempting to access t ...

How to prevent writing to the z-buffer for a specific object in Three.js

I have been attempting to prevent a write to the z-buffer for a specific object in three.js. This is what my code currently looks like: mesh.onBeforeRender = function(renderer){renderer.context.depthMask(false)}; mesh.onAfterRender = function(renderer){r ...

Guide to "flashing" an image momentarily on the screen using PHP

I'm looking for a way to display an image on my simple website for 3 seconds and then prompt the user to indicate if they recognized the image or not by clicking a button. I don't need help with the button, just how to create the timer. While I ...

What is the best way to keep a text editable in a razor editor without it vanishing?

I'm on a quest to find the name for a certain functionality that has been eluding me, and it's truly driving me up the wall. Check out the razor code snippet I've been using to exhibit my form inputs: <div class="col-sm"> ...

What could be causing the issue with <p> and style display:block not functioning as expected

Struggling with HTML coding on my website. The issue is that the <p> tags and elements with style="display:block" are appearing in one line instead of separate lines. Each block should be on its own line. Using Bootstrap 4.0.0 beta 2. https://i.ssta ...

Weird occurrences observed when JSON wraps my objects

I am sending the following request to my server: $.ajax({ url: url, data: JSON.stringify({ SecretKey: e.Code, CommentId: e.Id, Direction: direction, VoteType:1}), type: "POST", contentType: "application/json;charset=utf-8", }); After the ...