Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 71 ยท Components and Interaction

Button, TouchableHighlight, ActivityIndicator, Switch and ImageBackground

Use React Native's small built-in components well: Button props, TouchableHighlight timing, ActivityIndicator, Switch colors and ImageBackground with overlays.

Besides View, Text, Image and the list components, React Native ships a handful of small, single-purpose components. Each is easy to start with and has a few props that matter once you use it for real: the button that makes a sound you did not want, the spinner that must disappear, the switch that does not match your brand colors, the image with text on top. This lesson goes through them together and builds a small settings-and-loading screen from the pieces.

What runs on this site. These are native components, so the real React Native code is read-only. The runnable examples are stand-ins: they implement the same props with HTML and the same logic (counting, timing, toggling) so you can see the behavior.

Button: the quick option

Button takes title and onPress, plus a few optional props:

Prop Meaning
title the label (required)
onPress called on tap (required)
color the text color on iOS, the background on Android
disabled ignores presses and dims the button
accessibilityLabel what a screen reader says if it should differ from title
touchSoundDisabled (Android) skip the system click sound
hasTVPreferredFocus (TV) take the focus first
nextFocusUp, Down, Left, Right, Forward (Android and TV) which element gets focus on arrow keys or Tab
testID for tests

The classic first example is a counter. Notice that the change function reads the previous value, so quick taps never lose an update:

JSX
import { useState } from 'react';
import { View, Text, Button } from 'react-native';

export function Counter() {
  const [count, setCount] = useState(0);
  const changeCount = (delta) => setCount((c) => c + delta);
  return (
    <View style={{ gap: 8, padding: 16 }}>
      <Text style={{ fontSize: 24 }}>Count: {count}</Text>
      <Button title="Add one" onPress={() => changeCount(1)} />
      <Button title="Remove one" onPress={() => changeCount(-1)} disabled={count === 0} />
    </View>
  );
}

Button cannot be restyled beyond color. For a rounded, icon or branded button use Pressable (see Touchables and Pressable).

TouchableHighlight: underlay and delays

TouchableHighlight is one of the older touchables: while pressed, it shows a coloured layer (the underlay) beneath its single child and fades the child a little. Props worth knowing:

  • underlayColor: the colour of that layer. Without it you get a dark default.
  • activeOpacity: how transparent the child becomes while pressed.
  • delayPressIn and delayPressOut: milliseconds to wait before the press-in feedback starts, and before the press-out feedback ends. A press-in delay stops the highlight flashing when the user is only starting to scroll.
  • onShowUnderlay and onHideUnderlay: callbacks for the feedback itself.
  • onPress, onPressIn, onPressOut, onLongPress, delayLongPress: the usual press events.

It accepts exactly one child, and that child must be a single native-style View. For new code Pressable with a function style does the same, with more control.

JSX
<TouchableHighlight
  underlayColor="#dbeafe"
  delayPressIn={80}
  onPress={open}
>
  <View style={styles.row}>
    <Text>Open the report</Text>
  </View>
</TouchableHighlight>
delayPressIn: highlight only after a real press (stand-in)

ActivityIndicator: a spinner

ActivityIndicator shows the platform's native spinner. It is the standard "loading" signal for network calls.

Prop Meaning
animating true (the default) spins; false stops
size "small" or "large"; on Android also a number of points
color the spinner color; set it explicitly so it shows on your background
hidesWhenStopped (iOS) hide it when animating is false (default true)

The typical pattern is a loading flag that swaps the spinner for the content, and the spinner is not left on screen with animating={false}, because hidesWhenStopped exists only on iOS, so a stopped indicator does not behave the same on both platforms:

JSX
function Profile({ userId }) {
  const { data, isLoading } = useUser(userId);

  if (isLoading) {
    return (
      <View style={{ flex: 1, justifyContent: 'center' }}>
        <ActivityIndicator size="large" color="#2563eb" accessibilityLabel="Loading profile" />
      </View>
    );
  }
  return <ProfileCard user={data} />;
}

Remember the accessibility label: a spinner is silent to a screen reader unless you give it one (or announce loading with a live region).

Switch: an on-off toggle

Switch is a controlled component: you own value and update it in onValueChange, which receives the new boolean.

JSX
const [enabled, setEnabled] = useState(false);

<Switch
  value={enabled}
  onValueChange={setEnabled}
  trackColor={{ false: '#cbd5e1', true: '#86efac' }}
  thumbColor={enabled ? '#16a34a' : '#f8fafc'}
  ios_backgroundColor="#cbd5e1"
  disabled={loading}
/>
  • trackColor takes { false, true }: the track in each state.
  • thumbColor is the knob. On iOS it is only set when you pass it; Android shows a different colour by default.
  • ios_backgroundColor is the track colour shown on iOS when the switch is off.
  • Put a visible label next to it and group the two with accessibilityRole="switch", so a screen reader announces "Notifications, switch, off".

If onValueChange does not update value (a common bug), the switch snaps back, because a controlled component only shows what you pass it.

ImageBackground: an image behind children

ImageBackground is an Image that can hold children, so text and buttons sit on top of a picture. It takes every Image prop (source, resizeMode, blurRadius, defaultSource, onLoad, onLoadStart, onLoadEnd, onError) plus:

  • style: for the outer container. Give it a size or flex: 1.
  • imageStyle: for the picture itself, for example { borderRadius: 16, opacity: 0.8 }. borderRadius in style clips nothing on its own, so use imageStyle.
  • imageRef: a ref to the inner Image.
JSX
<ImageBackground
  source={require('./assets/hero.jpg')}
  resizeMode="cover"
  blurRadius={2}
  style={{ height: 200, justifyContent: 'flex-end' }}
  imageStyle={{ borderRadius: 16 }}
>
  <View style={{ backgroundColor: 'rgba(0,0,0,0.4)', padding: 12 }}>
    <Text style={{ color: 'white', fontSize: 20 }}>Welcome back</Text>
  </View>
</ImageBackground>

Text on a photo is hard to read, so add a scrim: a semi-transparent dark layer behind the text as above. Use resizeMode="cover" to fill the area, and give a defaultSource or a background colour so there is no blank flash while the image loads.

Putting them together

The screen below uses a stand-in for each component: a hero ImageBackground, a Switch that is really controlled, a loading state with ActivityIndicator, and a counter with the add and remove buttons that matches the one above.

A small settings screen made of the built-in components

The spinner is shown while loading is true and removed afterwards instead of being left with animating={false}. The switch only changes because onValueChange stores the new value.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does delayPressIn on TouchableHighlight do?

    It postpones the press-in feedback so a quick touch, or the start of a scroll, does not flash the highlight.
  2. 2. Your Switch snaps back to off every time it is tapped. What is the most likely cause?

    Switch is controlled. If the state passed to value never changes, the component shows the old value again.
  3. 3. How do you give an ImageBackground rounded corners?

    imageStyle styles the image itself. The outer style only sizes the container.
  4. 4. What is the recommended way to hide an ActivityIndicator when loading is finished?

    Conditional rendering removes it on every platform. A stopped indicator depends on hidesWhenStopped, which is iOS only.

Summary

  • Button has title, onPress, color and disabled, plus Android and TV extras such as touchSoundDisabled and nextFocus*; use Pressable when you need styling.
  • TouchableHighlight takes one child, an underlayColor and optional delayPressIn and delayPressOut.
  • ActivityIndicator has size, color and animating; remove it instead of stopping it, and give it an accessibility label.
  • Switch is controlled: value plus onValueChange, with trackColor, thumbColor and ios_backgroundColor for styling.
  • ImageBackground puts children over an image; use imageStyle for the picture, a scrim for readability and a fallback while it loads.

Next: Platform APIs.