Last active
December 5, 2024 17:25
-
-
Save zacharytyhacz/7052c1a0811065cad5d35fbed93f31bf to your computer and use it in GitHub Desktop.
React Native Checkbox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useMemo } from 'react' | |
| import { Svg, Path } from 'react-native-svg' | |
| import { View, StyleSheet, Text, TouchableOpacity, PixelRatio, StyleProp, ViewStyle } from 'react-native'; | |
| type Props = { | |
| checked: boolean | |
| onChange: (checked: boolean) => void | |
| label: string | |
| disabled?: boolean | |
| } | |
| export const Checkbox: React.FC<Props> = ({ | |
| checked, | |
| onChange, | |
| label, | |
| disabled | |
| }) => { | |
| const checkboxStyle = useMemo(() => { | |
| const stylesToUse: StyleProp<ViewStyle>[] = [styles.checkbox] | |
| if (checked) { | |
| stylesToUse.push(styles.checkboxChecked) | |
| } | |
| return stylesToUse | |
| }, [checked]) | |
| const containerStyles = useMemo(() => { | |
| const stylesToUse: StyleProp<ViewStyle>[] = [styles.container] | |
| if (disabled) { | |
| stylesToUse.push({ opacity: 0.5 }) | |
| } | |
| return stylesToUse | |
| }, [disabled]) | |
| return ( | |
| <TouchableOpacity | |
| style={containerStyles} | |
| onPress={() => onChange(!checked)} | |
| disabled={disabled} | |
| accessibilityHint={label} | |
| accessibilityLabel={label} | |
| > | |
| <View style={checkboxStyle}> | |
| { checked && <Svg width="20" height="20" fill="#FFF" viewBox="0 0 256 256"><Path d="M232.49,80.49l-128,128a12,12,0,0,1-17,0l-56-56a12,12,0,1,1,17-17L96,183,215.51,63.51a12,12,0,0,1,17,17Z"></Path></Svg> } | |
| </View> | |
| <Text style={styles.label}>{label}</Text> | |
| </TouchableOpacity> | |
| ) | |
| } | |
| const styles = StyleSheet.create({ | |
| container: { | |
| flex: 1, | |
| flexDirection: 'row', | |
| alignItems: 'center', | |
| gap: 8, | |
| height: 40 // must be at least 40 for Google Playstore accessiblity standards | |
| }, | |
| label: { | |
| fontSize: 14, | |
| color: '#000', | |
| }, | |
| checkbox: { | |
| width: 22 * PixelRatio.getFontScale(), | |
| height: 22 * PixelRatio.getFontScale(), | |
| borderRadius: '50%', | |
| borderWidth: 1, | |
| borderColor: '#C7C7CC', | |
| justifyContent: 'center', | |
| alignItems: 'center', | |
| }, | |
| checkboxChecked: { | |
| borderColor: '#007AFF', | |
| backgroundColor: '#007AFF' | |
| }, | |
| }); |
Author
zacharytyhacz
commented
Dec 5, 2024

Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
