A situation where the event onclick fails to occur within NextJS

index.js:


function Home () {
    return <div>
        <html>
       
 <head>
<title>Site</title> 
</head>


<body>
 
 
 <div class= 'v5_3' onclick = "func_click()"></div> 


 </body>
    
        </html>
        
        </div>
    
    }
    
function func_click() {
   
   
    alert('ALERT!!');


        }
        export default Home ; func_click

I'm currently working on a project using nextjs and running it locally with the command npm run dev. This process was learned from a tutorial video found at this link (video timestamp: 19:00 to 21:50). However, I encountered an issue where clicking on the button inside the 'v5_3' div doesn't trigger the JavaScript function, even though the styles for 'v5_3' are defined in the main.css file as follows:

.v5_3 {  
  width: 150px;
  height: 50px;
  color: white;
  background: rgb(5, 5, 5);
  opacity: 1;
  position: absolute;
  top: 30px;
  left: 1171px;
  border-top-left-radius: 30px;
  border-top-right-radius: 30px;
  border-bottom-left-radius: 30px;
  border-bottom-right-radius: 30px;
  
  
}

This CSS file is imported by the _app.js file:

import './main.css'

export default function MyApp({ Component, pageProps }) {
    return <Component {...pageProps} />
  }

All these files are located in the pages folder:

The alert functionality within the func_click() JavaScript function is not working. Any ideas on how to resolve this issue?

Answer №1

In the world of Next.js, it's important to understand that it is a framework built on top of React.js. Therefore, handling clicks in Next.js follows the same principles as React.

To start, you should define the click function within the component for better code organization. Although not mandatory, it enhances the structure of your code.
Next, make sure to reference the function using the camelcased onClick attribute along with the bracket syntax onClick={funcClick} to link the click event with the div element.

When working with classes, remember to use className instead of class. In frameworks like React and Next.js, these elements are treated as objects rather than traditional HTML elements. So, className is actually a property of an HTMLElement object.

function Home() {

  const funcClick = () => {
    alert("ALERT!!");
  };

  return (
    <div>
      <html>
        <head>
          <title>Site</title>
        </head>

        <body>
          <div className="v5_3" onClick={funcClick}></div>
        </body>
      </html>
    </div>
  );
}

export default Home;

Answer №2

Dealing with a similar problem, I was able to overcome it successfully. Turns out, the culprit was the z-index. Make sure to review your css settings.

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

Steps for changing an image with another image upon button click in Angular 6

I have a button with an image and text. When the button is clicked, I want to change both the image and content. Here's the code I'm currently using: <div class="btn-default"> <button name="Save" [ngClass]="[bntStyle]" (click)="submit ...

Is there a way to execute a Node 6 npm package within a Node 5.6.0 environment?

I am currently utilizing a tool called easy-sauce to conduct cross-browser JavaScript tests. Essentially, my package.json file references this tool for the test command: { "scripts": { "test": "easy-sauce" } } Everything runs smoothly when I exec ...

The React component fails to render on the screen

Upon retrieving data from the database server, attempts to render it result in the data being shown in the console log but not displayed in the component. What could be causing this issue? useEffect(() => { readRequest().then(setTodos); c ...

The SSE emitter sends out multiple signals, but occasionally the browser fails to receive them

When setting up an event emitter in a node.js/express application, I noticed that the events emitted are sometimes received multiple times by the front-end listener. Although I can confirm that emit is only called once, the same event gets emitted up to 4 ...

A guide on setting up dual observables in Angular 2

Currently, I am implementing Observable in angular 2 with rxjs. As part of my demonstration, I have utilized fromEvent in a Plunker. Here is the link to my demo: https://plnkr.co/edit/zkgEcdn21CvIKoOycUOy?p=preview In this demo, I have included two input ...

Using Express.js to Query a PostgreSQL Database via URL Parameters

Trying to retrieve specific information from my database via URL query is proving tricky. Currently, the response just displays all individuals in the database. exports.getPersonByName = async (req, res) => { const query = req.query.q try{ const per ...

How to create a heading within a Bootstrap list item?

Attempting to replicate this layout using Bootstrap 3 This is my current progress <ul class="list-group"> <li class="list-group-item> Cras justo odio </li> <li class="list-group-item> Dapibus ac facilisis in </l ...

I need to see the image named tree.png

Could someone assist me in identifying the issue with this code that only displays the same image, tree.png, three times? var bankImages = ["troyano", "backup", "tree"]; jQuery.each( bankImages, function( i, val ) { $('#imagesCon ...

Experiencing problems with the response from the Netlify Lambda function.. consistently receiving undefined results

I've been working on setting up a lambda function to handle authentication, validation, and sending of a contact form. As I'm new to lambda functions, my code might have some flaws. However, despite my efforts, I am struggling to modify the resp ...

Adding several <div> elements with the correct indices

I need help with a dynamic form that requires users to select a state before revealing the corresponding cities within that state. <form method="post"> <div class="summary"> <div class="trip"> <select name="State" class="s ...

Having trouble accessing data beyond the login page using Node/Express

Currently in an unusual situation. I am developing a backend and frontend that connects to a third-party RESTFUL API managing some hardware. The third-party API is hosted on your local system as a webserver, meaning HTTP requests are directed to "localhost ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

The disappearance of hashtag (#) when passed as req.query in the backend has been observed

I am facing an issue where a string with a hashtag in the req.query is not being parsed correctly as JSON. http://localhost:3000/link/?items=[{"quantity":1,"_id":"00001","box":"item01","desc":&quo ...

Tips for repairing a horizontal line at the bottom of the <TD> tag and placing text on top

I am working with an HTML table that contains a single TR tag and two TD tags. Each TD has two HR tags creating horizontal lines, along with some text. I am looking for a way to keep the text aligned at the top of the TD and the horizontal line at the bott ...

Utilizing a callback function to update the value of a variable that is declared outside of the getJSON function

I'm currently facing an issue with this function I have. function customCheck(username){ var result = "normal"; $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){ if(data.stream == null) re ...

Stop a hyperlink from refreshing the webpage

Currently, I am in the process of developing a responsive menu. You can view a demo of my progress on Codepen. In order to prevent the page from reloading when I click a link within the menu, I have implemented the following JavaScript code: $('nav. ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...

Body section CSS selector

Can a CSS selector be included within the body section of an HTML document? Here's an example of my code (although it is not functioning as expected): <html> <head> </head> <body> <div style= "a[target=_blank] {backgroun ...

Transmitting the Flag between PHP and JavaScript

I need help with setting a flag in PHP and accessing it in JavaScript. Currently, I have the following code: PHP if ($totalResults > MAX_RESULT_ALL_PAGES) { $queryUrl = AMAZON_SEARCH_URL . $searchMonthUrlParam . ...

AngularJS | Using ngAnimate to Display Form Validation Errors

My form errors are currently being displayed successfully using CSS and conditional classes, but I recently discovered ng-message and ng-animate. Would it be possible to use ng-message to contain the error messages? Also, I have been unable to find any tu ...