Bird
Raised Fist0
React Nativemobile~5 mins

Switch and checkbox patterns in React Native

Choose your learning style10 modes available
Introduction

Switches and checkboxes let users turn options on or off easily. They help make apps interactive and clear.

To let users enable or disable settings like notifications or dark mode.
To select multiple options from a list, like choosing favorite fruits.
To confirm choices, such as agreeing to terms and conditions.
To toggle features on or off, like turning on location services.
To quickly show a yes/no or true/false choice in forms.
Syntax
React Native
import React, { useState } from 'react';
import { View, Switch, Text, Pressable } from 'react-native';

function MyComponent() {
  const [isSwitchOn, setIsSwitchOn] = useState(false);
  const [isChecked, setIsChecked] = useState(false);

  return (
    <View>
      <Switch
        value={isSwitchOn}
        onValueChange={setIsSwitchOn}
      />
      <Pressable
        onPress={() => setIsChecked(!isChecked)}
        style={{
          width: 44,
          height: 44,
          justifyContent: 'center',
          alignItems: 'center'
        }}
      >
        <View
          style={{
            width: 24,
            height: 24,
            borderWidth: 2,
            borderColor: isChecked ? '#007AFF' : '#ccc',
            backgroundColor: isChecked ? '#007AFF' : 'transparent',
            borderRadius: 4
          }}
        />
      </Pressable>
    </View>
  );
}

Switch is used for toggling between two states, like ON/OFF.

Custom CheckBox (using Pressable + View) is used for selecting or deselecting an option.

Examples
This example shows a simple switch that toggles between true and false.
React Native
const [isEnabled, setIsEnabled] = useState(false);

<Switch
  value={isEnabled}
  onValueChange={setIsEnabled}
/>
This example shows a checkbox that the user can check or uncheck.
React Native
const [checked, setChecked] = useState(false);

<Pressable
  onPress={() => setChecked(!checked)}
  style={{width: 44, height: 44, justifyContent: 'center', alignItems: 'center'}}
>
  <View
    style={{
      width: 24,
      height: 24,
      borderWidth: 2,
      borderColor: checked ? '#007AFF' : '#ccc',
      backgroundColor: checked ? '#007AFF' : 'transparent',
      borderRadius: 4
    }}
  />
</Pressable>
A switch that is always ON and cannot be changed by the user.
React Native
<Switch
  value={true}
  disabled={true}
/>
Sample App

This app shows a switch to turn notifications on or off and a custom checkbox to accept terms. The text below updates to show the current choices. The checkbox is made accessible with roles and states.

React Native
import React, { useState } from 'react';
import { View, Text, Switch, Pressable, StyleSheet } from 'react-native';

export default function App() {
  const [isSwitchOn, setIsSwitchOn] = useState(false);
  const [isChecked, setIsChecked] = useState(false);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Switch and Checkbox Example</Text>

      <View style={styles.row}>
        <Text style={styles.label}>Enable Notifications</Text>
        <Switch
          value={isSwitchOn}
          onValueChange={setIsSwitchOn}
          accessibilityLabel="Enable Notifications Switch"
        />
      </View>

      <Pressable
        style={styles.checkboxContainer}
        onPress={() => setIsChecked(!isChecked)}
        accessibilityRole="checkbox"
        accessibilityState={{ checked: isChecked }}
        accessibilityLabel="Accept Terms Checkbox"
      >
        <View style={[styles.checkbox, isChecked && styles.checked]} />
        <Text style={styles.label}>Accept Terms and Conditions</Text>
      </Pressable>

      <Text style={styles.status}>
        Notifications are {isSwitchOn ? 'ON' : 'OFF'}
      </Text>
      <Text style={styles.status}>
        Terms accepted: {isChecked ? 'Yes' : 'No'}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
    backgroundColor: '#fff'
  },
  title: {
    fontSize: 24,
    marginBottom: 20,
    fontWeight: 'bold',
    textAlign: 'center'
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20
  },
  label: {
    fontSize: 18
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20
  },
  checkbox: {
    width: 24,
    height: 24,
    borderWidth: 2,
    borderColor: '#555',
    marginRight: 10,
    borderRadius: 4
  },
  checked: {
    backgroundColor: '#007AFF',
    borderColor: '#007AFF'
  },
  status: {
    fontSize: 16,
    marginTop: 10
  }
});
OutputSuccess
Important Notes

React Native's built-in CheckBox is deprecated on some platforms; a custom checkbox using Pressable and View can be used instead.

Always add accessibility labels and roles so screen readers can describe switches and checkboxes.

Use state hooks like useState to track the on/off or checked/unchecked status.

Summary

Switches toggle between two states, like ON/OFF.

Checkboxes let users select or deselect options.

Use state to control their values and update UI accordingly.

Practice

(1/5)
1. What is the main purpose of a Switch component in React Native?
easy
A. To toggle between two states like ON and OFF
B. To select multiple options from a list
C. To input text from the user
D. To display images in a gallery

Solution

  1. Step 1: Understand the Switch component

    A Switch is a UI element that lets users toggle between two states, usually ON or OFF.
  2. Step 2: Compare with other components

    Checkboxes allow multiple selections, text inputs accept text, and image galleries display images, so these do not match the Switch's purpose.
  3. Final Answer:

    To toggle between two states like ON and OFF -> Option A
  4. Quick Check:

    Switch toggles states = B [OK]
Hint: Switch means ON/OFF toggle, not multiple selections [OK]
Common Mistakes:
  • Confusing Switch with Checkbox
  • Thinking Switch accepts text input
  • Assuming Switch displays images
2. Which of the following is the correct way to declare a controlled Switch component in React Native?
easy
A. setIsOn(!isOn)} />
B. setIsOn(!isOn)} />
C. setIsOn(!isOn)} />
D. setIsOn(!isOn)} />

Solution

  1. Step 1: Recall Switch props in React Native

    The Switch component uses value to set its state and onValueChange as the event handler for toggling.
  2. Step 2: Identify correct syntax

    Options using checked or onChange are incorrect because React Native Switch does not use these props.
  3. Final Answer:

    <Switch value={isOn} onValueChange={() => setIsOn(!isOn)} /> -> Option D
  4. Quick Check:

    Switch uses value and onValueChange = C [OK]
Hint: Switch uses value and onValueChange props [OK]
Common Mistakes:
  • Using checked instead of value
  • Using onChange instead of onValueChange
  • Mixing HTML input props with React Native Switch
3. What will be the output on the screen after running this React Native code snippet?
const [checked, setChecked] = React.useState(false);

return (
  <CheckBox
    value={checked}
    onValueChange={() => setChecked(!checked)}
  />
);
If the user taps the checkbox once, what is the new value of checked?
medium
A. false
B. true
C. undefined
D. null

Solution

  1. Step 1: Initial state value

    The state variable checked starts as false.
  2. Step 2: Effect of tapping checkbox

    The onValueChange toggles checked to its opposite, so it becomes true after one tap.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    Toggle false once = true [OK]
Hint: Tapping toggles boolean state from false to true [OK]
Common Mistakes:
  • Assuming state stays false after tap
  • Confusing value prop with event
  • Thinking onValueChange returns new value
4. Identify the error in this React Native code for a controlled Switch:
const [isEnabled, setIsEnabled] = React.useState(false);

return (
  <Switch
    value={isEnabled}
    onChange={() => setIsEnabled(!isEnabled)}
  />
);
medium
A. Using value instead of checked
B. Missing initial state declaration
C. Using onChange instead of onValueChange
D. Not importing React

Solution

  1. Step 1: Check event handler prop

    The Switch component uses onValueChange to handle toggle events, not onChange.
  2. Step 2: Verify other parts

    The initial state is declared, value is correct, and React import is assumed correct.
  3. Final Answer:

    Using onChange instead of onValueChange -> Option C
  4. Quick Check:

    Switch needs onValueChange, not onChange [OK]
Hint: Switch uses onValueChange, not onChange [OK]
Common Mistakes:
  • Using onChange event instead of onValueChange
  • Confusing value and checked props
  • Forgetting to declare state
5. You want to create a list of three checkboxes in React Native where only one can be selected at a time (like radio buttons). Which approach correctly implements this behavior?
hard
A. Use three CheckBox components sharing one state variable that stores the selected option
B. Use one CheckBox component and change its label dynamically
C. Use three CheckBox components each with its own boolean state variable
D. Use three Switch components each with independent state variables

Solution

  1. Step 1: Understand single selection requirement

    Only one checkbox can be selected at a time, so all must share one state that tracks which is selected.
  2. Step 2: Evaluate options

    Use three CheckBox components sharing one state variable that stores the selected option. This uses one state variable to store the selected option and updates it on selection, ensuring only one is selected. Options A and C use independent states allowing multiple selections. Use one CheckBox component and change its label dynamically uses only one checkbox, which cannot represent three options.
  3. Final Answer:

    Use three CheckBox components sharing one state variable that stores the selected option -> Option A
  4. Quick Check:

    Single selection needs shared state = D [OK]
Hint: Single selection means one state tracks selected checkbox [OK]
Common Mistakes:
  • Giving each checkbox its own state allowing multiple selections
  • Using Switch instead of CheckBox for selection list
  • Trying to reuse one checkbox for multiple options
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard