Show a Checkbox in React Native



Checkboxes is a common component that we often use on the UI. We do have some cool ways of showing checkboxes in reactnative.

The core react-native package does not have checkbox support and you need to install a package to work with it.

Following package has to be installed to display checkbox −

npm install --save-dev react-native-paper

The basic checkbox component is as follows −

<Checkbox status={checkboxstatus} onPress={onCheckboxCheckedfunc} />

Let us now see some important properties on checkbox −

Props Description
status The value that can be given to status are checked, unchecked and indeterminate.
disabled The value is boolean.It can be used to enable/disable the checkbox.
onPress The function that will be called when the checkbox is checked.
color The color to be given to the checkbox
uncheckColor The color for the checkbox in unchecked mode.

Here is a simple checkbox display −

The useState is used to set the checked , unchecked status for the checkbox as shown below −

const [checked, setChecked] = React.useState(false);

The state is maintained inside checked variable and setChecked method is used to update it.

The checked status will be updated when user checks/unchecks the checkbox as shown below −

onPress={() => {
   setChecked(!checked);
}}

The complete code is as follows −

Example

import * as React from 'react';
import { StyleSheet, Text, SafeAreaView } from 'react-native';
import { Checkbox } from 'react-native-paper';
const MyComponent = () => {
   const [checked, setChecked] = React.useState(false);
   return (
      <SafeAreaView style={styles.container}>
         <Checkbox
            status={checked ? 'checked' : 'unchecked'}
            onPress={() => {
               setChecked(!checked);
            }}
            color={'green'}
            uncheckColor={'red'}
         />
      <Text>Checkbox</Text>
      </SafeAreaView>
   );
};
const styles = StyleSheet.create({
   container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center'
   },
});
export default MyComponent;

Output

Updated on: 2021-07-01T09:28:06+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements