CodeBlanks Logo Icon CodeBlanks

Button

Learn the Button component and its onPress.

Button

The Button component in React Native is the most basic touch element. It has two required props: title sets the button label and onPress sets the function that handles the tap. Example: <Button title="Save" onPress={handleSave} />.

Button ships with the default look of the operating system; customization is limited to the color prop. When you need a more custom look you reach for TouchableOpacity or Pressable. Button accepts only a plain text label and cannot host other components inside.

The onPress handler

onPress takes a function that runs when the user taps and releases the button. The function is usually defined inside the component with a name like handleSave or onSubmit. Important: you write onPress={handleSave} to pass a reference; no parentheses.

Wrong form: onPress={handleSave()}. This calls the function once during render and hands the result to onPress, which is rarely what you want. Correct: onPress={handleSave} or, with an arrow, onPress={() => handleSave(id)}.

Practice Write a Save button

Complete the empty App component. Define a handleSave function (its body may be empty). Return <Button title="Save" onPress={handleSave} />.

Starter code

App.js
import React from 'react';
import { Button } from 'react-native';

export default function App() {
  // Add the handleSave function and return a Button
  return null;
}

Sample solution

App.js
import React from 'react';
import { Button } from 'react-native';

export default function App() {
  const handleSave = () => {};
  return <Button title="Save" onPress={handleSave} />;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which prop sets the label on Button?

App.js
<Button ???="Save" onPress={save} />
  • title Correct answer
  • label
  • text
  • name

Explanation: The title prop sets the button label.

2 Write the onPress reference

Question
<Button title="Save" ____={handleSave} />
Answer
<Button title="Save" onPress={handleSave} />

Explanation: onPress takes the tap function.

3 Match each prop to its job

Term Meaning
title Button label
onPress Tap function
color Button color
disabled Disable the button

All lessons in Beginner