Home > Back-end >  Unsure why console.log is not being called upon button click next.js
Unsure why console.log is not being called upon button click next.js

Time:09-07

I'm trying to do a simple task, just to log something to the console when a button is clicked but for some reason, it is not working. I'm using Next.js web app template by Startup Agency and I am not sure why it is not logging to the console. Upon starting the app, this is what I see in the console even though I didn't even click the button:

hello
GA init
Logging pageview for /product

And when I click the button, nothing appears in the console and I'm not sure why that is. This is the link to the website I am using the template from in case you need it. Here is my code:

export default function Product() {
  return (
      <div style={styles.container}>
          <div style={styles.speechTitle}>Talk to us, tell us about your day...</div>
          <div style={styles.speechBox}>

          </div>
          <button onClick={console.log('hello')}>Hello</button>
      </div>

  );
}

CodePudding user response:

The onClick handler takes a function as value. So instead of passing console.log('hello') which literally return the string 'hello', you need to create the function (a.k.a handler).

export default function Product() {
  function clickHandler(event){
    console.log("hello")
  }
  return (
          <button onClick={clickHandler}>Hello</button>
  );
}

or use an arrow function if you only need one button to do the job.

export default function Product() {
  return (
          <button onClick={(e) => {console.log("hello")}}>Hello</button>
  );
}

read more about events in react

CodePudding user response:

You need to return the console.log from a function



export default function Product() {
  return (
      <div style={styles.container}>
          <div style={styles.speechTitle}>Talk to us, tell us about your day...</div>
          <div style={styles.speechBox}>

          </div>
          <button onClick={()=>console.log('hello')}>Hello</button>
      </div>

  );
}
  • Related