Skip to content

Instantly share code, notes, and snippets.

@ashwin1014
Last active May 20, 2021 15:13
Show Gist options
  • Save ashwin1014/e17deffdf17d17320cac2fc21c9f84af to your computer and use it in GitHub Desktop.
Save ashwin1014/e17deffdf17d17320cac2fc21c9f84af to your computer and use it in GitHub Desktop.
Radio Button Group React Native
import React, { memo, useCallback } from "react";
import { View, Pressable, Text, StyleSheet } from "react-native";
import PropTypes from "prop-types";
import Space from "./Space/Space";
/**
* @param items = [{ name: "Good Morning", value: "greet_morning" }, { name: "Good Evening", value: "greet_evening" }]
*/
const styles = StyleSheet.create({
radioButton: {
alignItems: "flex-start",
flex: 1
},
radioWrapper: {
height: 24,
width: 24,
borderRadius: 12,
borderWidth: 2,
borderColor: "#00A8C3",
alignItems: "center",
justifyContent: "center"
},
radioSelected: {
height: 12,
width: 12,
borderRadius: 6,
backgroundColor: "#00A8C3"
}
});
const noop = () => undefined;
const RadioIcon = React.memo(function RadioIcon({
checked = false,
label = ""
}) {
return (
<Space>
<View style={styles.radioWrapper}>
{checked ? <View style={styles.radioSelected} /> : null}
</View>
<Text>{label}</Text>
</Space>
);
});
const RadioGroup = ({
items = [],
onChange = noop,
value,
direction = "vertical",
disabled = false
}) => {
const handleRadioSelect = useCallback(
val => {
onChange(val);
},
[onChange]
);
return (
<Space direction={direction} size="md">
{(items || []).map(item => (
<Pressable
key={item.value}
disabled={disabled}
style={styles.radioButton}
onPress={() => handleRadioSelect(item.value)}
>
<RadioIcon checked={value === item.value} label={item.name} />
</Pressable>
))}
</Space>
);
};
RadioGroup.propTypes = {
direction: PropTypes.oneOf(["horizontal", "vertical"]),
items: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
.isRequired
})
).isRequired,
onChange: PropTypes.func.isRequired,
disabled: PropTypes.bool,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired
// style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
};
RadioIcon.propTypes = {
checked: PropTypes.bool.isRequired,
label: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};
export default memo(RadioGroup);
@ashwin1014
Copy link
Author

usage:

  import RadioGroup from './RadioGroup';
 
  const [value, setValue] = React.useState('greet_morning');
  const items = [
    { name: "Good Morning", value: "greet_morning" },
    { name: "Good Evening", value: "greet_evening" }
  ];

 <RadioGroup items={items} value={value} onChange={setValue} />

radio

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