Learn

Besides all visual components, every app requires interactive components. One of the most frequent interactions is a “click” or “press” interaction. Most of the core components have support for press interactions. But, there is one component specifically created to handle simple presses: the Button component.

Although the Button is very limited in styling customization, it’s perfect for learning or prototyping purposes.

To capture the user clicking the button, we need to use the onPress event handler. This is called onPress because there usually is no mouse available on a mobile device.

<Button title="Profile page" onPress={() => navigate('profile')} />

Simple press interactions can be anything from submitting a form to navigating to a different page.

Instructions

1.

Let’s start by experimenting with the onPress event handler on the Button. This event handler is a required property on the Button, that’s why it has a handler that is returning null.

In this code, we want to keep track of how many times the Button is pressed by the user. Change the onPress event handler to increase the pressed count state variable every time the button is pressed.

2.

Awesome! Now try to press the button. The text should reflect how many times you pressed the button. This example demonstrates the core principles of event handlers, methods invoked by user interaction. These event handlers can also perform bigger actions, like navigating to another screen or sending data to an API.

Sometimes we need to disable certain user interactions when the event handler is performing a bigger task. Sending data to an API should finish fairly quickly. Unfortunately, sometimes internet connections aren’t great, and the HTTP request can take a couple of seconds. Disabling the Button to avoid sending the data twice during this period can improve the user experience.

Let’s add a property to our Button that disables the Button after pressing it 3 or more times.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?