import * as React from "react"; import { StyleSheet, StyleProp, ViewStyle, GestureResponderEvent, } from "react-native"; import color from "color"; import { DefaultTheme, ThemeContext } from "styled-components"; import IconButton from "../IconButton"; import { ToggleButtonGroupContext } from "./ToggleButtonGroup"; import { black, white } from "../theme/colors"; type Props = { /** * Icon to display for the `ToggleButton`. */ icon: React.ReactElement; /** * Size of the icon. */ size?: number; /** * Custom text color for button.s */ color?: string; /** * Whether the button is disabled. */ disabled?: boolean; /** * Accessibility label for the `ToggleButton`. This is read by the screen reader when the user taps the button. */ accessibilityLabel?: string; /** * Function to execute on press. */ onPress?: (value?: GestureResponderEvent | string) => void; /** * Value of button. */ value?: string; /** * Status of button. */ status?: "checked" | "unchecked"; style?: StyleProp; /** * @optional */ theme?: DefaultTheme; }; /** * Toggle buttons can be used to group related options. To emphasize groups of related toggle buttons, * a group should share a common container. * *
* *
* * ## Usage * ```js * import * as React from 'react'; * import ToggleButton from 'react-native-simple-elements/components/ToggleButton'; * * const ToggleButtonExample = () => { * const [status, setStatus] = React.useState('checked'); * * const onButtonToggle = value => { * setStatus(status === 'checked' ? 'unchecked' : 'checked'); * }; * * return ( * * ); * }; * * export default ToggleButtonExample; * * ``` */ const ToggleButton = ({ icon, size, accessibilityLabel, disabled, style, value, status, onPress, ...rest }: Props) => { const theme = React.useContext(ThemeContext); const borderRadius = theme.roundness; return ( {(context: { value: string; onValueChange: (evt?) => void } | null) => { let backgroundColor; const checked: boolean | null = (context && context.value === value) || status === "checked"; if (checked) { backgroundColor = theme.dark ? "rgba(255, 255, 255, .12)" : "rgba(0, 0, 0, .08)"; } else { backgroundColor = "transparent"; } return ( { if (onPress) { onPress(e); } if (context) { context.onValueChange(!checked ? value : null); } }} size={size} accessibilityLabel={accessibilityLabel} accessibilityState={{ disabled, selected: checked }} disabled={disabled} style={[ styles.content, { backgroundColor, borderRadius, borderColor: color(theme.dark ? white : black) .alpha(0.29) .rgb() .string(), }, style, ]} {...rest} /> ); }} ); }; const styles = StyleSheet.create({ content: { width: 42, height: 42, margin: 0, }, }); export default ToggleButton; // @component-docs ignore-next-line const ToggleButtonWithTheme = ToggleButton; // @component-docs ignore-next-line export { ToggleButtonWithTheme as ToggleButton };