Create your own radio button component in react native easily

saadbashar

Saad

Posted on April 11, 2019

Create your own radio button component in react native easily

You can easily create your own radio button components in react native very easily. First you need to create an array of options for your radio buttons and pass it to your radio button component like so:

const options = [
    {
        key: 'pay',
        text: 'Most High Pay',
    },
    {
        key: 'performance',
        text: 'Most Perfomance',
    },
    {
        key: 'aToZ',
        text: 'A - Z',
    },
    {
        key: 'zToA',
        text: 'Z - A',
    },
];

{...}
<RadioButtons options={options} />
Enter fullscreen mode Exit fullscreen mode

after this in your radio button component you can map all these options in your render method and create radio button views

{options.map(item => {
    return (
        <View key={item.key} style={styles.buttonContainer}>
            <Text>{item.text}</Text>
            <TouchableOpacity style={styles.circle} />
        </View>
    });
}
Enter fullscreen mode Exit fullscreen mode

this will create default radio buttons which looks like this -

default

Right now it is time to set the state when clicked on the radio button. First we declare our state

state = { value: null }

then inside out tag we define our checked button when clicked on any particular button.

<TouchableOpacity
    style={styles.circle}
    onPress={() => this.setState({ value: key })} // we set our value state to key
>
    { value === item.key && (<View style={styles.checkedCircle} />) } // when value is equal to key
</TouchableOpacity>
Enter fullscreen mode Exit fullscreen mode

So right now when clicked it looks like this -

checked

finally the styles -

buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 30,
},
circle: {
    height: 20,
    width: 20,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#ACACAC',
    alignItems: 'center',
    justifyContent: 'center',
},
checkedCircle: {
    width: 14,
    height: 14,
    borderRadius: 7,
    backgroundColor: '#794F9B',
},
Enter fullscreen mode Exit fullscreen mode

Here is the snack link - https://snack.expo.io/@saad-bashar/radio-buttons

💖 💪 🙅 🚩
saadbashar
Saad

Posted on April 11, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related