fbpx

How To Create and Implement Checkboxes Using React Native?

blog_detail_img

July 10 , 2020 Posted by Creatix9

Checkboxes are one of the most commonly used components in an app’s user interface. On both android and iOS platforms, you may need to include checkboxes to allow a user to select or deselect items or options. React-native app development has seen a boom in recent years, and many mobile app development companies have integrated react-native developers into their teams. Using this how-to guide, you will be able to create and implement a react-native android or iOS app.

The main reason we have to custom create checkboxes is because react native does not provide a checkbox component by default, so either we design it from scratch, or include any available checkbox component found on the internet. 

Now I will explain the process that we need to follow to implement a react native checkbox.

  • The initial step is to create a simplistic class to manage the data. This class will have the objects of the checkboxes which were selected by the user, which will be useful further on.
  • Then we will create a new component named Check_Box, which will be used to create our checkbox’s design as well change the state of the checkbox.
  • Next we will create a main component that will contain the objects for Check_Box and the data managing class. 

These are the main steps of the process to create and implement the checkbox in react native. You may go further by customizing the checkbox to your liking by changing its size, labels, color etcetera, but we won’t go into that.

 

So, let’s then get down to the details:

1. First start by creating a new react native app.

2. Next we need to install prop-types, an external library into your new react native app. This library allows the developer to allow validation checks on their custom-created components, which allows us to check and rectify issues like missing property values etcetera. The command to install it is:

npm install – save prop-types

3. After that is done installing, we will open up index.andriod.js, or for the iOS environment index.ios.js file in the code editor of your choice, and remove all code written in it by default. We will be following a for-scratch methodology in order to understand the entire process better.

4. Next we will import all the necessary components, from react and react-native libraries. The code structure is as follows:

 

import React, { Component } from ‘react’;

import {View, TouchableHighlight, Text, Stylesheet, Image, AppRegistry, Platform } from ‘react-native’;

import PropTypes from ‘prop-types’;

 

5. Finally, we will now be creating the class which will handle the data.

 

class MyReactArr

{

constructor()

{

itemsSelect = [];

}

enterItem(option)

{

itemsSelect.push(option);

}

getArr()

{

return itemsSelect;

}

}

The enterItem method is created to enter the selected checkbox into the array, while the getArr method is to get the array of all checkboxes which were selected.

6. Now we will create our own checkbox component, which will contain our design and the function required to toggle the checkbox state.

 

class Check-Box extends Component

{

   constructor()

   {

      super();

 

      this.state = { checked: null }

   }

 

   compMount()

   { }

 

   stateToggle = (key, label) =>

   { }

 

   render()

   {

      return( );

   }

}

The compMount() method will compare values of the checkbox object and if they are “True”, then the checkbox will be entered into the array. The stateToggle() method is used to toggle the state of the checkboxes, and the render() method creates and returns the design with the initial values.

 

7. Implement the compMount() method. When the app loads, we will monitor the checked parameter and then set the checked state to true to make an entry into the array.

 

compMount()

{

  if(this.props.checked)

  {

    this.setState({ checked: true }, () =>

    {

      this.props.selectedArrayObject.setItem({ ‘key’: this.props.keyValue, ‘label’: this.props.label });

    });

  }

  else

  {

    this.setState({ checked: false });

  }

}

selectedArrayObject is a necessary parameter which needs to be passed by each object of the checkbox from our main component, as it holds the reference to the array from our data handling class. So we can then use it to access the methods of our data handling class.

 

8. Now we will implement the method to toggle state

 

stateToggle(key, label)

{

  this.setState({ checked: !this.state.checked }, () =>

  {

     if(this.state.checked)

     {

        this.props.selectedArrayObject.setItem({ ‘key’: key, ‘label’: label });

     }

     else

     {

        this.props.selectedArrayObject.getArr ().splice( this.props.selectedArrayObject.getArr().findIndex(x => x.key == key), 1 );

     }

  });

}

 

9. Next we will implement the code for the design of our unique checkbox component

 

return(

  <TouchableHighlight onPress = { this.toggleState.bind(this, this.props.keyValue, this.props.label) } underlayColor = “transparent” style = { styles.checkBoxButton }>

     <View style = { styles.checkBoxHolder }>

        <View style = {{ width: this.props.size, height: this.props.size, backgroundColor: this.props.color, padding: 2 }}>

        {

           (this.state.checked)

           ?

              (<View style = { styles.checkedView }>

                 <Image source = { require(‘./assets/check.png’) } style = { styles.checkedImage }/>

              </View>)

           :

              (<View style = { styles.uncheckedView }/>)

        }

        </View>

        <Text style = {[ styles.checkBoxLabel, { color: this.props.color }]}>{ this.props.label }</Text>

     </View>

  </TouchableHighlight>

);

 

10. After that we will implement the code for the main component, where we can create many instances of the checkbox component we created above.

 

class App extends Component

{

  constructor()

  {

    super();

 

    selectArrRef = new MyReactArr (); 

  }

 

  getSelectedItems = () =>

  {

    if( selectArrRef.getArr ().length == 0 )

    {

      alert(‘No Item(s) Selected!’);

    }

    else

    {

      console.log(selectArrRef.getArr ());

    }    

  }

 

  render()

  {

    return(

        <View style = { styles.container }>

          <Checkbox size = { 30 } keyValue = { 1 } selectedArrayObject = { selectArrRef } checked = { true } color = “#636c72” label = “Item #1″/>

          <Checkbox size = { 35 } keyValue = { 2 } selectedArrayObject = { selectArrRef } checked = { true } color = “#0275d8” label = “Item #2″/>

          <Checkbox size = { 40 } keyValue = { 3 } selectedArrayObject = { selectArrRef } checked = { true } color = “#5cb85c” label = “Item #3″/>

          <Checkbox size = { 45 } keyValue = { 4 } selectedArrayObject = { selectArrRef } checked = { true } color = “#f0ad4e” label = “Item #4″/>

          <Checkbox size = { 50 } keyValue = { 5 } selectedArrayObject = { selectArrRef } checked = { true } color = “#d9534f” label = “Item #5″/>

 

          <TouchableHighlight underlayColor = “rgba(0,0,0,0.6)” style = { styles.selectedArrayItemsBtn } onPress = { this.getSelectedItems }>

            <Text style = { styles.btnText }>Get Selected</Text>

          </TouchableHighlight>

        </View>

    );

  }

}

 

11. At this stage you may set the styles for the different components as per your need, but we won’t be doing that at the moment.

12. After that, we will implement validation checks using prop-types

 

Checkbox.propTypes =

{

  size: PropTypes.number,

  keyValue: PropTypes.number.isRequired,

  selectedArrayObject: PropTypes.object.isRequired,

  color: PropTypes.string,

  label: PropTypes.string,

  checked: PropTypes.bool

}

 

13. We also need to provide the default values for the properties above with the help of prop-types.

 

Checkbox.defaultProps =

{

  size: 30,

  color: ‘#636c72’,

  label: ‘Default’,

  checked: false

}

 

14. Finally, after all the effort we went through, we will publish our personalized app with AppRegistry.

 

AppRegistry.registerComponent(‘App’, () => App);

 

15. To test the app on our android or iOS devices, we can do it by running the following scripts, as per your platform.

 

– Android

react-native run-android

 

– iOS

react-native run-ios

 

If you followed and understood the steps detailed above, you will now be able to create and implement check-boxes of different descriptions for any react-native app you build. 

Happy Coding 😉

Leave a Reply

Your email address will not be published. Required fields are marked *