'React: Button onClick function is running on page load but not you click it
I am using the ButtonGroup and Button from ReactStrap. I have set an onClick function when you click one of the buttons:
< ButtonGroup >
<Button>Edit</Button>
<Button onClick={console.log("Print some text")}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
But when I load the page this is what I get:

Before I have even clicked the button. And if I do click it, nothing comes out in the console. Any ideas?
Solution 1:[1]
onClick parameter is evaluated as a callback, so if you pass something that is not a function, is evaluated and executed in the runtime.
Instead, you should pass a function to the onClick parameter:
<Button onClick={() => { console.log("Print some text"); }}>Print text</Button>
Be careful with the inline functions because they are evaluated each time that render is executed, that can be multiple times, each functions is more memory used by the browser.
If you has a class, you can use a arrow fat method:
/* ... */
handleOnClick = () => {
console.log("Print some text");
}
render() {
return (
<ButtonGroup>
<Button>Edit</Button>
<Button onClick={this.handleOnClick}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
);
}
/* ... */
Solution 2:[2]
To make it clearer
On any event trigger (onClick, onChange , etc) you must specified a function to call when the event occur not calling the function right away
Consider this function
ES5:
function callMe() {
console.log("Some text");
}
ES6:
const callMe = () => {
console.log("Some text");
}
if you want to call this function when clicking the button you can't do this
<Button onClick={callMe()}>Print text</Button>
This will call the fuction callMe when the button is loaded once. What you need to do to make it works is
<Button onClick={callMe}>Print text</Button>
Notice that there is no parenthesis after the function name which indicate that the function is not yet called.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Táboas |
| Solution 2 | BAXMAY |
