Reputation: 349
I am new to both JavaScript and ReactJS and want to understand why the following pieces of code differ in behaviour:
class App extends React.Component
{
render()
{
return (
<button onClick={() => {alert("Hello World!");}}>Hello!</button>
);
}
};
The above code works as expected. A button is shown on the page, and when the button is clicked an alert message "Hello World!" is displayed.
But the following code does not work as expected:
class App extends React.Component
{
alertText = (text) => {
alert(text);
}
/*
alertText(text) {
alert(text);
}
*/
render()
{
return (
<button onClick={this.alertText("Hello World!")}>Hello!</button>
);
}
};
I was expecting this code to work similar to the first piece of code. Instead, two alert messages with the text "Hello World!" are displayed in succession immediately after the page is launched without the button being clicked. But after that nothing happens when the button is clicked.
My platform is Ubuntu 20.04.1, nodejs is v10.19.0 and npx is 6.14.4, browser is Firefox 80.0 Ubuntu build. I created the React app with npx create-react-app
command.
Upvotes: 0
Views: 25
Reputation: 4420
well because you always call functions in your render, in the first one you call arrow function which returns the alrt function which would be called on click, on the other hand you call directly the alert.
Upvotes: 0
Reputation: 11171
Because the code tell them to behave differently. onClick
expect a function. this.alertText("Hello World!")
is not a function, you just call the function right away. It should be
render()
{
return (
<button onClick={() => this.alertText("Hello World!")}>Hello!</button>
);
}
Upvotes: 1