Behind the scenes, buttons in React behave like pure JavaScript buttons. The advantage is that you can put the event directly in the button without creating a variable to reference the button.
Pre-requisites
Arrow functions: A video that will help you convert normal functions to arrow functions to be comfortable reading React code.
Intended result
Figure 1: A simple page with 2 buttons.
Figure 2: App hierarchy diagram.
Legend:
- ๐ฆ Blue: Component created by us.
- โป๏ธ Grey: Normal tags.
Getting started
There are many ways to create button events in React, but let's focus on 2. They depend if you want to call a function without passing arguments or if you need to pass arguments.
ย
Calling a function without passing arguments:
export default function App() {
function myFunction() {
alert("You click me");
}
return (
<div className="App">
<button onClick={myFunction}>Click me</button>
</div>
);
}
Let's analyze the code:
-
function myFunction() {}
Is the function called when you click on a button. -
onClick={myFunction}
theonClick
property will fire the function that you pass to it.
Note: We don't put parenthesis in the function inside onClick. Doing so will run the function when the page load, and then the button won't work when the user clicks on it.
ย
Calling a function that needs to pass arguments:
export default function App() {
function myGreet(name) {
alert(`Hello ${name}`);
}
return (
<div className="App">
<button onClick={() => myGreet("Ana")}>Click me</button>
</div>
);
}
Let's analyze the code:
-
function myGreet(name){}
The function to run, note that it has an argument. -
onClick={() => myGreet("Eduardo")}
In order to pass a function with arguments, we need to create a function on the fly, inside the onClick event. When the user clicks on the button, it will call the arrow function, thus, running any code inside it.
Here is where the arrow function comes to fruition. This allows us to write a shorter syntax to avoid making our JSX messy.
Finally, you can pass as many arguments as you want. But to be organized, stick to 1 or 2 arguments. If you need to pass more arguments, use an object or array for better organization.
Conclusion
This article will allow you to practice how to use buttons to modify information on the screen by manipulating the state.
The next article is Form events in React that goes deeper into the state, so users can submit data to your application.
In you want to see the finished code open this link and open the branch buttons.
Additional reading
Handling Events official React documentation
Credits:
Cover photo: Photo by Matthew T Rader on Unsplash
Top comments (0)