When using React, the page loads and triggers all onClick events simultaneously, but when clicking on a button, no action is taken

I have a strong foundation in HTML and CSS/SASS but I'm just getting started with React. Recently, I encountered an issue that has me stumped.

I am trying to highlight a button on the navigation bar based on the current page the user is on.

I attempted to add a simple onClick event handler to the buttons which would trigger a function passing in a string like "home" or "contact".

After adding an alert() to the function for testing, I noticed that upon loading the page, every button's method was called resulting in multiple alerts. Subsequently, clicking the buttons seemed ineffective as if the onClick event was never added.

Could someone please point out where I might be going wrong with this straightforward function? I've been grappling with it for the past few hours and would greatly appreciate any insights.

Thank you!

NavBar.js:

function NavBar() {

const isActive = "home";


return (    
  <nav className="landing-page__nav-bar nav-bar">
  <ul className="nav-bar__list">
    <Link to ='/home'><li><a data-page="home" className="home-link">
      <button href="landingpage" className={` ${isActive === "home" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("home")}>Home</button>
      </a></li>
    </Link>
    <Link to ='/portfolio'><li><a data-page="portfolio" className="portfolio-link">
      <button className={` ${isActive === "portfolio" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'`} } onClick={buttonWasClicked("portfolio")}>Portfolio</button>
      </a></li>
      </Link>
    <Link to ='/artwork'><li><a data-page="doodles" className="doodles-link">
    <button className={` ${isActive === "artwork" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("artwork")}>Artwork</button>
      </a></li></Link>
    <Link to ='/photography'><li><a data-page="photography" className="photography-link">
      <button className={` ${isActive === "photography" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("photography")}>Photography</button>
      </a></li></Link>
    <Link to ='/cv'><li><a data-page="cv" className="cv-link">
    <button className={` ${isActive === "cv" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("cv")}>CV</button
      ></a></li></Link>
    <Link to ='/about'><li><a data-page="about" className="about-link">
    <button className={` ${isActive === "about" ? 'btn__nav-basr-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("about")}>About</button>
      </a></li></Link>
    <Link to ='/contact'><li><a data-page="contact" className="contact-link">
    <button className={` ${isActive === "contact" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("contact")}>Contact</button>
      </a></li></Link>       
  </ul>
</nav>

);
  }

    export default NavBar;

ButtonClick.js (method to update the current page):

import NavBar from './Nav-bar';

function ChangeActiveButton(selectedButton) {

    alert(selectedButton)
    NavBar.isActive = toString(selectedButton);
}

export default ChangeActiveButton;

Answer №1

Instead of directly calling the function when rendering and passing the result to the button's onClick, it would be better to assign an anonymous function to the onClick event. This function should call the desired function with the correct parameter when executed.

<button className={` ${isActive === "profile" ? 'btn__nav-profile-btn active-link' : 'btn__nav-profile-btn'}`} onClick={() => handleClick("profile")}>Profile</button>

Answer №2

onClick attribute must be assigned a function, not to invoke a function directly. Writing buttonWasClicked("contact") will trigger the function as soon as the DOM is loaded.

To avoid this, you should use

{() => buttonWasClicked("contact")}

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

What is causing the mouse to malfunction when interacting with this HTML form?

What is causing the mouse to not work with the form on this specific webpage? The issue here is that the mouse does not seem to be functioning correctly when attempting to interact with the input boxes within the Form. Upon clicking any of the input boxe ...

Troubleshooting the issue of having multiple menu items in Material UI

Every time I attempt to add the Menu component multiple times, I encounter an issue with the popup list displaying incorrectly. To demonstrate this problem, you can view it through the link provided on codesandbox below. I have included data-id attributes ...

Printing without sufficient paper will result in an incomplete printout

https://i.stack.imgur.com/jNlRr.jpg I am facing an issue with printing the last column "Potensi". The text in this column is not fully printed. How can I resolve this problem? I am using PHP. Thank you ...

Error: Unable to interpret the URL provided in /api/posts/1

When working on my next.js 13 app, I encountered an issue while trying to fetch individual blog data from a local MySQL database. In the src/blog/[id]/page.js file, I have the following component: const BlogPost = async ({ params }) => { const data ...

Can you clarify the semver meaning of the >= operator and what is the highest version it permits?

It's commonly known that when using symbols like ^, it represents anything up to the next major version, and ~ means only patches. However, there seems to be a lack of clarity regarding what the maximum version is when utilizing >=. So, how should ...

What is the best way to mark a MenuItem as active within a Material UI Drawer component?

Here is the code snippet I am working with: <Drawer docked = {false} width = {330} open = {this.state.drawerOpen} onRequestChange = {(drawerOpen) => this.setState({drawerOp ...

How can I implement user-specific changes using Flask?

I am a beginner with Flask and I am working on a project where users can sign up, and if the admin clicks a button next to their name, the user's homepage will change. Below is the Flask code snippet: from flask import Flask, redirect, url_for, render ...

Error: An unidentified SyntaxError occurred with an unexpected token < within an anonymous function displayed on the console

In the process of developing an upload file application. The implementation involves AJAX and PHP. Everything functions smoothly on the localhost, but upon transferring it to the web server, a specific error is encountered: Uncaught SyntaxError: Unexpe ...

Function exhibiting varying behavior based on the form from which it is called

Currently, I'm utilizing AJAX to execute a server call, and I've noticed that the behavior of my function varies depending on its origin. Below is an excerpt of the code that's causing confusion: <html> <body> <script> ...

Intersecting table columns with a different data table

My task is to create a table with a column that contains another table, where I want the colors of each alternating row to be different. Please refer to the image below (ignore the "CharacterAgain" column). Below is an example of AngularJS code for the ta ...

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

Is there a way to efficiently include numerous jQuery scripts in a batch process, each with a slight variation, using a loop?

Currently, I have a script that calculates the blur effect for multiple images based on the mouse position and scroll position. However, I am looking for a more efficient way to apply this to around 100 images without duplicating the script each time. var ...

Is there a way to maintain formdata between components in Angular?

With only the tools of @Input, @Output, routing, and activatedRoute at my disposal, I set out to create a dynamic application. In this project, there are two crucial components: addbook and showbook. The addbook component features a form with a submit bu ...

Are there problems with the response values of functions that can handle varying object interfaces?

Currently in the process of developing a command line blackjack app with Node and Typescript, even though I am relatively new to Typescript. My main challenge lies in implementing interfaces for player and dealer objects, as well as creating functions that ...

Propagating Exceptions in React Native

Check out this function geolocate() that asynchronously calls a geolocation service in React Native. The issue at hand is that when an error occurs within the geolocationError() function, it doesn't get passed up to the parent geolocate(), resulting ...

Accessing a subcollection with DocumentSnapshot in Firebase using JS9

Just had a quick question. Is anyone familiar with how to achieve something similar using Firebase JavaScript v9? Essentially, I have a `userDoc` that is a DocumentSnapshot and I need to access a sub-collection with the document snapshot. Here's the c ...

Next.js is having trouble loading Tailwindcss colors from a variable value

I am currently working on creating a card component within Next.js, with multiple color options. However, I am facing an issue where the Tailwind colors are not being recognized when I attempt to utilize them. Card.tsx: interface Props { // Adding suppo ...

Unable to load the manually added module in the /node_modules/ folder

I'm trying to manually use a module that I placed in the /node_modules/ directory. After copying and pasting the files and installing dependencies with npm, I encountered an issue while using NWJS 0.16.0. When attempting var speech = require('sp ...

Obtain the name of the checkbox that has been selected

I'm new to JavaScript and HTML, so my question might seem silly to you, but I'm stuck on it. I'm trying to get the name of the selected checkbox. Here's the code I've been working with: <br> <% for(var i = 0; i < ...

Implementing MySQL in JavaScript code leads to various possibilities

I am working on a web application that requires retrieving values from a MySQL database. The process involves: PHP code generates an HTML page successfully. Clicking a button updates a cookie, which also works. Using the cookie in a MySQL query, which is ...