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: https://i.sstatic.net/FGa6O.png

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

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

Utilize JSON categories to assign groups to TextFields or Selects according to a JSON data attribute

I have retrieved multiple JSON groups from an API, each containing one or more questions objects. My goal is to display each question along with its corresponding response in a MUI TextField or Select component, based on the value of QuestionType. Current ...

"Changing background color, incorporating hover effects, utilizing !important, and manipulating .css properties with

Encountered a dilemma. I devised a "tabs" feature illustrated in the following demo: http://jsfiddle.net/4FLCe/ The original intention was for the tab to change color to A when hovered over, and to color B when clicked on. However, as shown in the demo, ...

Is it secure to store information that impacts component rendering within a JWT payload?

I am currently developing a MERN app where users have various roles, and different components are rendered based on their role in React. In my application, I store a JWT containing the user's ID and role in a cookie, which is then decoded in a global ...

Why aren't the validations being set when creating Angular forms using formControl.values?

I had to structure the form in a specific way in my app.ts file -> courseNameControl = new FormControl("", [Validators.required,Validators.minLength(2)]); contentControl = new FormControl("", Validators.required); form = { cours ...

Retrieve the total count of rows present in a specific table

Is there a way to accurately determine the number of rows in a table? I've attempted multiple methods (all unsuccessful) and this is my latest attempt: var _tableOfInterestsCount = wait.Until(x => x.FindElements(By.XPath("//*[@id='gridBody ...

Retrieve the position of an element using Python and selenium

Currently, I am working on a project and need to extract the location and size of an element using the following xpath: "//div[@class='titlu']" Upon inspection, it appears that the element is visible with no distinct features. However, I have e ...

Issue between Promise and EventEmitter causing race conditions in ExpressJS

Currently, I am working on a NodeJS/Express web application where users can upload files that are then parsed using the connect-busboy module and saved to a database with Sequelize. Once the data is stored, I aim to redirect the user to a specific page. Ho ...

How to design a trapezium shape using CSS and HTML

While there are many tutorials available for creating Trapezoids with CSS3, I am interested in making a four-sided shape where none of the sides are parallel (trapezium), similar to the one shown in the image below. Can this be achieved? ...

Ajax is updating the information stored in the Data variable

Recently, I reached out to tech support for help with an issue related to Ajax not executing properly due to Access-Control-Allow-Origin problems. Fortunately, the technician was able to resolve the issue by adding a file named .htaccess with the code Head ...

What is the method for inserting the document URL into a text input?

Can someone provide guidance on grabbing the top URL and inserting it into a text input field? I've tried the following method, but it's not working. Any suggestions or ideas? Additionally, is there a way to make this text input field uneditable? ...

What is the best way to showcase text formatting applied in Strapi's WYSIWYG editor in NextJS's user interface?

I'm a beginner with Next JS and Strapi CMS. Trying to figure out how to transfer styling from the backend admin panel in Strapi to the UI in NextJS. Is there a way to display the formatted text created in Strapi's WYSIWYG editor on the frontend ...

Troubleshooting the "Failed to mount component" error in Vue: fixing template or render function definition issues

Struggling with writing a Vue component, encountering the issue: Failed to mount component: template or render function not defined. Tried various fixes like adding default when importing the component, but none of them seem to work. My component code is i ...

No sweat / Possibly NextJS / Could it be that maybeGetServerSnapshot isn't a recognized function?

Encountering an issue with the latest versions of easy-peasy (5.2.0), NextJS (12.1.6), and React (18.1.0) where easy-peasy throws an error when using `useStoreState` stating `TypeError: maybeGetServerSnapshot is not a function`. The code snippet causing th ...

Creating a POST request in Rails 3

Is there a way to integrate web services in Rails 3 by sending POST parameters to an external URL? Typically, I utilize a command line method like the one below for posting: curl -X POST -u "v10REVkw:XuCqIhyCw" \ -H "Content-Type: application/json" & ...

Encountering an error in resolving symbol values statically within the Angular module

Following a helpful guide, I have created the module below: @NgModule({ // ... }) export class MatchMediaModule { private static forRootHasAlreadyBeenCalled: boolean = false; // This method ensures that the providers of the feature module ar ...

Steps for aligning a grid column to the same height as the element above it and moving it to the left side

I have a setup using material UI where I have a grid positioned on top of a Paper element. Within the grid, there is a text input field in the first column that I want to match the height of the paper element and be aligned with its left border. I have tri ...

Utilize Material-UI slider components to dynamically manage slider handles

I am trying to dynamically create sliders based on user input and struggling with saving values when they are changed. Below is the code snippet I have implemented so far. The issue I'm facing is that I cannot retrieve the value using event.target.val ...

The process of incorporating the dymo.framework into an Angular project

My Angular project is currently in need of importing dymo.connect.framework. However, I am facing some challenges as the SDK support provided by dymo only explains this process for JavaScript. I have also referred to an explanation found here. Unfortunate ...

When utilizing Reactjs, accessing an element by its id becomes challenging when the element is nested within a map() function

Currently, I am encountering an issue related to reactjs. In my scenario, I have a requirement to compare the height of the screen with a specific div to determine its maximum width. The challenge lies in the fact that the particular div I need to analyz ...