Home > Software design >  React: onClick is not triggering
React: onClick is not triggering

Time:09-24

I am trying out React for a fairly easy project, and as a beginner, I started by trying to create a simple clickable button that would lead to a popup alert.

The code looks like this:

import "./styles.css";
import React from "react";

export default function App() {
  
   const handleClick =()=>{
   alert("Random text");
   }
  
   return (
   <div>
       <button onClick={() => handleClick()}>BUTTON</button>
   </div>
   );
}

Or, the click can be handled like this, with the same result:

function handleClick(){
        alert("Random text");
      }

Alternatively, the onClick event can be attributed like this, with the same result:

return (
    <div>
     <button onClick={handleClick}>BUTTON</button>
    </div>
  );

The issue: After running this through VSCode on a browser, I am returned the button exactly like it is supposed to be, but when I click on it nothing pops up.

If I change <button onClick={handleClick}>BUTTON</button> to <button onClick={handleClick()}>BUTTON</button> the alert renders before the button and the webpage, and the button click still returns nothing.

The exact same pieces of code, when run on React sandbox return the expected result. So, my guess is there may be an issue with VSCode, or the React installation. I rarely ran into issues with VSCode in the past, so I have not yet tried a different IDE for this project.

Any assistance or hint would be greatly appreciated! Thank you!

CodePudding user response:

The code works fine. There must be a problem with your installation of react or something in this category...

  • Related