UNPKG

2.8 kBTypeScriptView Raw
1import * as React from 'react';
2import { StyleSheet, View, StyleProp, ViewStyle } from 'react-native';
3import ToggleButtonGroup from './ToggleButtonGroup';
4import ToggleButton from './ToggleButton';
5
6type Props = {
7 /**
8 * Function to execute on selection change.
9 */
10 onValueChange: (value: string) => void;
11 /**
12 * Value of the currently selected toggle button.
13 */
14 value: string;
15 /**
16 * React elements containing toggle buttons.
17 */
18 children: React.ReactNode;
19 style?: StyleProp<ViewStyle>;
20};
21
22/**
23 * Toggle button row renders a group of toggle buttons in a row.
24 *
25 * <div class="screenshots">
26 * <figure>
27 * <img class="medium" src="screenshots/toggle-button-row.gif" />
28 * </figure>
29 * </div>
30 *
31 * ## Usage
32 * ```js
33 * import * as React from 'react';
34 * import { ToggleButton } from 'react-native-paper';
35 *
36 * const MyComponent = () => {
37 * const [value, setValue] = React.useState('left');
38 *
39 * return (
40 * <ToggleButton.Row onValueChange={value => setValue(value)} value={value}>
41 * <ToggleButton icon="format-align-left" value="left" />
42 * <ToggleButton icon="format-align-right" value="right" />
43 * </ToggleButton.Row>
44 * );
45 * };
46 *
47 * export default MyComponent;
48 *
49 *```
50 */
51const ToggleButtonRow = ({ value, onValueChange, children, style }: Props) => {
52 const count = React.Children.count(children);
53
54 return (
55 <ToggleButtonGroup value={value} onValueChange={onValueChange}>
56 <View style={[styles.row, style]}>
57 {React.Children.map(children, (child, i) => {
58 // @ts-expect-error: TypeScript complains about child.type but it doesn't matter
59 if (child && child.type === ToggleButton) {
60 // @ts-expect-error: We're sure that child is a React Element
61 return React.cloneElement(child, {
62 style: [
63 styles.button,
64 i === 0
65 ? styles.first
66 : i === count - 1
67 ? styles.last
68 : styles.middle,
69 // @ts-expect-error: We're sure that child is a React Element
70 child.props.style,
71 ],
72 });
73 }
74
75 return child;
76 })}
77 </View>
78 </ToggleButtonGroup>
79 );
80};
81
82ToggleButtonRow.displayName = 'ToggleButton.Row';
83
84const styles = StyleSheet.create({
85 row: {
86 flexDirection: 'row',
87 },
88 button: {
89 borderWidth: StyleSheet.hairlineWidth,
90 },
91
92 first: {
93 borderTopRightRadius: 0,
94 borderBottomRightRadius: 0,
95 },
96
97 middle: {
98 borderRadius: 0,
99 borderLeftWidth: 0,
100 },
101
102 last: {
103 borderLeftWidth: 0,
104 borderTopLeftRadius: 0,
105 borderBottomLeftRadius: 0,
106 },
107});
108
109export default ToggleButtonRow;
110
111// @component-docs ignore-next-line
112export { ToggleButtonRow };