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>
);
};
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With