How to show a checkbox in reactnative?

React NativeJavascriptMobile Development

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 −

PropsDescription
statusThe value that can be given to status are checked, unchecked and indeterminate.
disabledThe value is boolean.It can be used to enable/disable the checkbox.
onPressThe function that will be called when the checkbox is checked.
colorThe color to be given to the checkbox
uncheckColorThe 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

raja
Published on 01-Jul-2021 09:28:06
Advertisements