Build React Native Custom Checkbox Component for Android and iOS

Last updated on by Digamber
In this tutorial, we are going to learn how to create a custom Checkbox component in React Native application for Android and iOS platforms. We will learn step by step how to get Multiple checkboxes values on button click using React Native APIs.

Android Checkbox Example

The Checkbox is and HTML element. It is a square box that can be checked (ticked) or unchecked, and it is used to select any number of values among given options.

Checkboxes are used when there is a list of options, and the user may select any number of choices, including zero, one, or several. In other words, each checkbox is independent of all other checkboxes in the list, and checking one box doesn’t uncheck the others.
uxplanet.org

Let’s get started.

Prerequisite

To build custom Checkbox component in React Native for iOS and Android. We should have following tools, frameworks, and packages.

  • Node.js
  • NPM
  • React-Native
  • React-Native CLI
  • IDE or Text Editor
  • Xcode for iOS
  • Android Studio

Create React Native App

Run command to install latest React Native CLI globally in your device.

npm install -g react-native-cli

Install brand new React Native app.

react-native init rncheckbox

Get inside the project folder.

cd rncheckbox

Verify React Native’s installed version.

react-native -v

# react-native-cli: 2.0.1
# react-native: 0.61.5

React Native Custom Checkbox Component Example

The checkbox is a UI element that has two-states checked or unchecked.

Configure Checkbox Asset

To build the custom checkbox for Android or iOS platform via React Native, we have to create an assets folder at the root of our project. Also, save the tick.png there, we will be using this image to show the checked state for the checkbox.

Download the tick.png.

Import React Native APIs

Next, open the App.js file and import following APIs at the top of the App component file. FYI, We will be writing all the code related to Android or iOS Checkboxes example in App.js.

import React, { Component } from 'react';
import { 
  Alert, 
  Image, 
  Platform, 
  StyleSheet, 
  Text, 
  TouchableHighlight, 
  View 
} from 'react-native';
API Detail
Alert: Display an alert modal with the specified title and message.
Image: Shows several types of images, including network images, static resources, temporary local images, and images from local disks, such as the camera roll.
Platform: This module identifies the platform in which the app is working.
StyleSheet: This API works similarly as CSS StyleSheets.
Text: This component helps in displaying the text.
TouchableHighlight: A wrapper for composing views responds appropriately to touches.
View: This is a container that supports layout with flexbox, style, some touch handling, and accessibility controls.

Also, Import PropTypes from from ‘prop-types’. It allows us to define custom types and props for Android or iOS React Native checkbox component.

import PropTypes from 'prop-types';

Check out the documentation to know more about React Native API.

Next, define SelectedCheckboxes class in App component. This class is responsible for managing the selected checkboxes elements. The addItem() method adds checked item into an array whereas the fetchArray() gets the checked item in an array form.

class SelectedCheckboxes {
  constructor() {
    selectedCheckboxes = [];
  }

  addItem(option) {
    selectedCheckboxes.push(option);
  }

  fetchArray() {
    return selectedCheckboxes;
  }
}

Create CheckBox Class

Next, we will create the custom checkbox component class below the Selected_Checkbox_Array class. Also, define the constructor method and set super() class and the initial checked state to null.

class Checkbox extends Component {
  
  constructor() {
    super();
    this.state = { 
      checked: null 
    }
  }
  
}

Next, declare componentDidMount() life cycle hook inside the Checkbox class. This method allows us to verify the state based on the value and trigger the addItem() method of SelectedCheckboxes. It has 3 value for checkbox component — key, value and label.

componentDidMount() {
    if (this.props.checked) {
      this.setState({ checked: true }, () => {
        this.props.checkedObjArr.addItem({
          'key': this.props.keyValue,
          'value': this.props.value,
          'label': this.props.label
        });
      });
    } else {
      this.setState({ 
        checked: false
      });
    }
  }

Maintain Checkbox Selected and Unselected State

Next, create stateSwitcher() function right after componentDidMount() method. It deals with the selected and unselected state, also add the checkbox values in the array when checkbox value is chosen.

stateSwitcher(key, label, value) {
    this.setState({ checked: !this.state.checked }, () => {
      if (this.state.checked) {
        this.props.checkedObjArr.addItem({ 
          'key': key,
          'value': value,
          'label': label
        });
      } else {
        this.props.checkedObjArr.fetchArray().splice(
          this.props.checkedObjArr.fetchArray().findIndex(y => y.key == key), 1
        );
      }
    });
  }

Build Checkbox View with TouchableHighlight

Next, set up the Checkbox view inside the Checkbox class using TouchableHighlight API. This code will also trigger the stateSwitcher() method with the help of the onPress event of TouchableHighlight.

render() {
    return (
      <TouchableHighlight
        onPress={this.stateSwitcher.bind(this, this.props.keyValue, this.props.label, this.props.value)} 
        underlayColor="transparent"
        style={{ marginVertical: 20 }}>

        <View style={{ 
          flexDirection: 'row', 
          alignItems: 'center' }}>
            <View style={{
              padding: 4, 
              width: this.props.size, 
              height: this.props.size, 
              backgroundColor: this.props.color
            }}>
              {
                (this.state.checked)
                  ?
                  (<View style={styles.selectedUI}>
                    <Image source={require('./assets/tick.png')} style={styles.checkboxTickImg} />
                  </View>)
                  :
                  (<View style={styles.uncheckedCheckbox} />)
              }
          </View>
          <Text style={[styles.checkboxLabel, { color: this.props.labelColor }]}>
            {this.props.label}
          </Text>
        </View>

      </TouchableHighlight>
    );
  }

Here is the final code for Checkbox Class.

class Checkbox extends Component {

  constructor() {
    super();
    this.state = { 
      checked: null 
    }
  }

  componentDidMount() {
    if (this.props.checked) {
      this.setState({ checked: true }, () => {
        this.props.checkedObjArr.addItem({
          'key': this.props.keyValue,
          'value': this.props.value,
          'label': this.props.label
        });
      });
    } else {
      this.setState({ 
        checked: false
      });
    }
  }
 
  stateSwitcher(key, label, value) {
    this.setState({ checked: !this.state.checked }, () => {
      if (this.state.checked) {
        this.props.checkedObjArr.addItem({ 
          'key': key,
          'value': value,
          'label': label
        });
      } else {
        this.props.checkedObjArr.fetchArray().splice(
          this.props.checkedObjArr.fetchArray().findIndex(y => y.key == key), 1
        );
      }
    });
  }

  render() {
    return (
      <TouchableHighlight
        onPress={this.stateSwitcher.bind(this, this.props.keyValue, this.props.label, this.props.value)} 
        underlayColor="transparent"
        style={{ marginVertical: 20 }}>

        <View style={{ 
          flexDirection: 'row', 
          alignItems: 'center' }}>
            <View style={{
              padding: 4, 
              width: this.props.size, 
              height: this.props.size, 
              backgroundColor: this.props.color
            }}>
              {
                (this.state.checked)
                  ?
                  (<View style={styles.selectedUI}>
                    <Image source={require('./assets/tick.png')} style={styles.checkboxTickImg} />
                  </View>)
                  :
                  (<View style={styles.uncheckedCheckbox} />)
              }
          </View>
          <Text style={[styles.checkboxLabel, { color: this.props.labelColor }]}>
            {this.props.label}
          </Text>
        </View>

      </TouchableHighlight>
    );
  }
}

Define default App Component

Next, we declare the default App Component using the export keyword. Here, we will define the super() class, CheckedArrObject object, and pickedElements.

export default class App extends Component {
 
  constructor() {
    super();
    CheckedArrObject = new SelectedCheckboxes();
    this.state = { pickedElements: '' }
  }
 
}

On Button Click Display Selected Items

Next, we need to define the function renderSelectedElements in App Component. This will get all the checked checkbox elements on button Press.

renderSelectedElements = () => {
    if (CheckedArrObject.fetchArray().length == 0) {
      Alert.alert('No Item Selected');
    } else {
      this.setState(() => {
        return {
          pickedElements: CheckedArrObject.fetchArray().map(res => res.value).join()
        }
      });
    }
 }

Next, define the Checkbox component in the main App Component class. We need to set the size, label, value, labelColor, color, checked, checkedObjectArray, and keyValue properties in the Checkbox component along with a button that will get all the selected element when a user clicks on this button.

render() {
    return (
      <View style={styles.CheckboxContainer}>
        <Checkbox size={45}
          keyValue={1}
          checked={true}
          color="#E81E63"
          labelColor="#000000"
          label="Birds of Prey"
          value="birds_of_prey" 
          checkedObjArr={CheckedArrObject} />

        <Checkbox size={45}
          keyValue={2}
          checked={false}
          color="#3F50B5"
          labelColor="#000000"
          label="Little Women"
          value="little_women" 
          checkedObjArr={CheckedArrObject} />

        <Checkbox size={45}
          keyValue={3}
          checked={true}
          color="#009688"
          labelColor="#000000"
          label="Doctor Sleep"
          value="doctor_sleep"
          checkedObjArr={CheckedArrObject} />

        <Checkbox size={45}
          keyValue={4}
          checked={false}
          color="#FF9800"
          labelColor="#000000"
          label="Ford v Ferrari"
          value="ford_v_ferrari"
          checkedObjArr={CheckedArrObject} />        

        <TouchableHighlight style={styles.showSelectedButton} onPress={this.renderSelectedElements}>
          <Text style={styles.buttonText}>Checked Items</Text>
        </TouchableHighlight>
        <Text style={{ fontSize: 22, color: "#000", marginTop: 25 }}> {this.state.pickedElements} </Text>
      </View>
    );
  }
}

Setting up Default Value to Checkbox Props

Next, we will add the Default values to Checkbox Props, add the below code right after the export default class App closes.

Checkbox.propTypes = {
    keyValue: PropTypes.number.isRequired,
    size: PropTypes.number,
    color: PropTypes.string,
    label: PropTypes.string,
    value: PropTypes.string,
    checked: PropTypes.bool,
    labelColor: PropTypes.string,
    checkedObjArr: PropTypes.object.isRequired
}

Checkbox.defaultProps = {
    size: 32,
    checked: false,
    value: 'Default',
    label: 'Default',
    color: '#cecece',
    labelColor: '000000',    
}

Style React Native Checkbox Component

Next, we will style the Checkboxes component by adding the CSS styling via StyleSheet.create() method. Add the following code right after the Default Value to Checkbox Props.

const styles = StyleSheet.create(
  {
    CheckboxContainer: {
      flex: 1,
      padding: 22,
      alignItems: 'center',
      justifyContent: 'center',
      paddingTop: (Platform.OS === 'ios') ? 25 : 0
    },

    showSelectedButton: {
      padding: 20,
      marginTop: 25,
      alignSelf: 'stretch',
      backgroundColor: '#5D52FF'
    },

    buttonText: {
      fontSize: 20,
      color: '#ffffff',
      textAlign: 'center',
      alignSelf: 'stretch'
    },

    selectedUI: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center'
    },

    checkboxTickImg: {
      width: '85%',
      height: '85%',
      tintColor: '#ffffff',
      resizeMode: 'contain'
    },

    uncheckedCheckbox: {
      flex: 1,
      backgroundColor: '#ffffff'
    },

    checkboxLabel: {
      fontSize: 18,
      paddingLeft: 15
    }
});

Full Code for Checkbox Component

import React, { Component } from 'react';
import { 
  Alert, 
  Image, 
  Platform, 
  StyleSheet, 
  Text, 
  TouchableHighlight, 
  View 
} from 'react-native';
import PropTypes from 'prop-types';


class SelectedCheckboxes {
  constructor() {
    selectedCheckboxes = [];
  }

  addItem(option) {
    selectedCheckboxes.push(option);
  }

  fetchArray() {
    return selectedCheckboxes;
  }
}

class Checkbox extends Component {

  constructor() {
    super();
    this.state = { 
      checked: null 
    }
  }

  componentDidMount() {
    if (this.props.checked) {
      this.setState({ checked: true }, () => {
        this.props.checkedObjArr.addItem({
          'key': this.props.keyValue,
          'value': this.props.value,
          'label': this.props.label
        });
      });
    } else {
      this.setState({ 
        checked: false
      });
    }
  }
 
  stateSwitcher(key, label, value) {
    this.setState({ checked: !this.state.checked }, () => {
      if (this.state.checked) {
        this.props.checkedObjArr.addItem({ 
          'key': key,
          'value': value,
          'label': label
        });
      } else {
        this.props.checkedObjArr.fetchArray().splice(
          this.props.checkedObjArr.fetchArray().findIndex(y => y.key == key), 1
        );
      }
    });
  }

  render() {
    return (
      <TouchableHighlight
        onPress={this.stateSwitcher.bind(this, this.props.keyValue, this.props.label, this.props.value)} 
        underlayColor="transparent"
        style={{ marginVertical: 20 }}>

        <View style={{ 
          flexDirection: 'row', 
          alignItems: 'center' }}>
            <View style={{
              padding: 4, 
              width: this.props.size, 
              height: this.props.size, 
              backgroundColor: this.props.color
            }}>
              {
                (this.state.checked)
                  ?
                  (<View style={styles.selectedUI}>
                    <Image source={require('./assets/tick.png')} style={styles.checkboxTickImg} />
                  </View>)
                  :
                  (<View style={styles.uncheckedCheckbox} />)
              }
          </View>
          <Text style={[styles.checkboxLabel, { color: this.props.labelColor }]}>
            {this.props.label}
          </Text>
        </View>

      </TouchableHighlight>
    );
  }
}

export default class App extends Component {
 
  constructor() {
    super();
    CheckedArrObject = new SelectedCheckboxes();
    this.state = { pickedElements: '' }
  }
 
  renderSelectedElements = () => {
    if (CheckedArrObject.fetchArray().length == 0) {
      Alert.alert('No Item Selected');
    } else {
      this.setState(() => {
        return {
          pickedElements: CheckedArrObject.fetchArray().map(res => res.value).join()
        }
      });
    }
  }

  render() {
    return (
      <View style={styles.CheckboxContainer}>
        <Checkbox size={45}
          keyValue={1}
          checked={true}
          color="#E81E63"
          labelColor="#000000"
          label="Birds of Prey"
          value="birds_of_prey" 
          checkedObjArr={CheckedArrObject} />

        <Checkbox size={45}
          keyValue={2}
          checked={false}
          color="#3F50B5"
          labelColor="#000000"
          label="Little Women"
          value="little_women" 
          checkedObjArr={CheckedArrObject} />

        <Checkbox size={45}
          keyValue={3}
          checked={true}
          color="#009688"
          labelColor="#000000"
          label="Doctor Sleep"
          value="doctor_sleep"
          checkedObjArr={CheckedArrObject} />

        <Checkbox size={45}
          keyValue={4}
          checked={false}
          color="#FF9800"
          labelColor="#000000"
          label="Ford v Ferrari"
          value="ford_v_ferrari"
          checkedObjArr={CheckedArrObject} />        

        <TouchableHighlight style={styles.showSelectedButton} onPress={this.renderSelectedElements}>
          <Text style={styles.buttonText}>Checked Items</Text>
        </TouchableHighlight>
        <Text style={{ fontSize: 22, color: "#000", marginTop: 25 }}> {this.state.pickedElements} </Text>
      </View>
    );
  }
}
 
Checkbox.propTypes = {
    keyValue: PropTypes.number.isRequired,
    size: PropTypes.number,
    color: PropTypes.string,
    label: PropTypes.string,
    value: PropTypes.string,
    checked: PropTypes.bool,
    labelColor: PropTypes.string,
    checkedObjArr: PropTypes.object.isRequired
}

Checkbox.defaultProps = {
    size: 32,
    checked: false,
    value: 'Default',
    label: 'Default',
    color: '#cecece',
    labelColor: '000000',    
}

const styles = StyleSheet.create(
  {
    CheckboxContainer: {
      flex: 1,
      padding: 22,
      alignItems: 'center',
      justifyContent: 'center',
      paddingTop: (Platform.OS === 'ios') ? 25 : 0
    },

    showSelectedButton: {
      padding: 20,
      marginTop: 25,
      alignSelf: 'stretch',
      backgroundColor: '#5D52FF'
    },

    buttonText: {
      fontSize: 20,
      color: '#ffffff',
      textAlign: 'center',
      alignSelf: 'stretch'
    },

    selectedUI: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center'
    },

    checkboxTickImg: {
      width: '85%',
      height: '85%',
      tintColor: '#ffffff',
      resizeMode: 'contain'
    },

    uncheckedCheckbox: {
      flex: 1,
      backgroundColor: '#ffffff'
    },

    checkboxLabel: {
      fontSize: 18,
      paddingLeft: 15
    }
});

Next, we will learn how to start the React Native app in the Xcode and Android Studio to show you the Android Checkbox example and iOS Checkbox example.

Android Checkbox Example

Run React Native Android App with Android Studio Emulator

Before we check Android Checkbox Example, i assume you have already installed Java SDK in your device. You can verify the version by using the below command.

java -version

# openjdk version "1.8.0_242"
# OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_242-b08)
# OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.242-b08, mixed mode)

Android Studio provides the fastest tools for building apps on every type of Android device. Click here to download Android Studio.

Next, we will set ANDROID_HOME, JAVA_HOME, ANDROID_HOME, ANDROID_SDK_ROOT, ANDROID_AVD_HOME, ANDROID_SDK, and platform-tools env variables in .bash_profile file.

Run command in your terminal to open the .bash_profile file.

vim  ~/.bash_profile

Add the following variables in the file. And, replace your computer name for ANDROID_SDK and PATH variables.

export JAVA_HOME=$(/usr/libexec/java_home)
export ANDROID_HOME=~/Library/Android/sdk       
export ANDROID_SDK_ROOT=~/Library/Android/sdk       
export ANDROID_AVD_HOME=~/.android/avd export

export ANDROID_SDK=/Users/<your-computer-name>/Library/Android/sdk
export PATH=/Users/<your-computer-name>/Library/Android/sdk/platform-tools:$PATH

Press ‘esc’ key and then type :wq to save and close the .vim file.

To verify if the path has been added, run the following command in the terminal.

source ~/.bash_profile
echo $JAVA_HOME

Next, go to your project’s android folder and create local.properties file and place the following code in it.

sdk.dir = /Users/digamber/Library/Android/sdk

Next, start the Android Virtual Device Manager using Android Studio, and run the following command to run Android app.

react-native run-android

Android Checkbox Example

iOS Checkbox Example

Run React Native iOS App with Xcode

We need to download and configure Xcode to test React Native’s iOS app version, follow the given below process.

  • Visit Apple Developer
  • Click on develop
  • Click on downloads and sign in
  • Scroll to the bottom and click see more downloads
  • Use the search bar to search up Xcode
  • Click the little plus icon on the row with the Xcode version you want
  • Click download on the zip file

From here you can download Xcode.

Set up the Xcode path for CLI, visit Xcode > Preferences > Locations Here set the Command Line Tools: Xcode xx.x.x (version number) from the dropdown.

Run React Native App in Xcode Emulator

Next, run the following command to install cocoapods.

sudo gem install cocoapods

Get inside the iOS directory of your project.

cd ios

Run the command from the iOS folder.

pod install

Get out from the iOS folder and run the command to run the iOS app.

react-native run-ios

iOS Checkbox Example

Conclusion

Finally, we have completed the React Native Checkbox tutorial, and in this tutorial, we have learned how to build Custom Checkbox Component for Android and iOS platforms with React Native.

You can download the complete code of this tutorial on this GitHub repository.

Happy Coding!

Avatar
Digamber

Digamber Rawat is from Uttarakhand, located in northwestern part of India. He is a Full-stack developer by profession and a primary author of this blog.