Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: onClick function executes before clicking button

Tags:

reactjs

The function SendCred() executes the page is loading, but I want this to be called when the user clicks the <button>. What should I do?

 import React,{useState} from "react";

    export default function Signup(props){

      const sendCred=()=>{
        console.log("test")
      };


      return (
        <div className="row container">
          <button onClick={sendCred()}> Activate Laser </button>
        </div>
      );

    };
like image 709
Dhiraj Baruah Avatar asked Apr 19 '26 10:04

Dhiraj Baruah


1 Answers

The sendCred function is being called directly, when the result of your functional component is being evaluated and returned:

{/* The sendCred() function is being evaluated during render, and the 
    result of sendCred is being passed to the onClick prop */
<button onClick={sendCred()}> Activate Laser </button>

To achieve the desired behavior, consider specifying the value passed to onClick as a callback function that wraps a call to sendCred() (ie an arrow function as shown below). By doing this, the arrow function will be passed to onClick and, when a user click invokes onClick, the supplied arrow function will be called which will in turn cause sendCred() to be called:

export default function Signup(props){

  const sendCred=()=>{
    console.log("test")
  };

  return (
    <div className="row container">
      {/* Wrap sendCred() with an arrow function, and pass the arrow
          function to onClick as the callback to be invoked for user 
          click events on button */}
      <button onClick={ () => sendCred() }> Activate Laser </button>
    </div>
  );
};

Alternatively, you could also just pass the sendCred function directly to onClick - the key here is to ensure that you do not include a parenthesis pair (as you currently have done), as doing so will cause sendCred to be invoked during render:

{ /* Omit the () after sendCred */ }  
<button onClick={ sendCred }> Activate Laser </button>
like image 89
Dacre Denny Avatar answered Apr 21 '26 01:04

Dacre Denny