Hussain Arif Hussain is a CS student in Pakistan whose biggest interest is learning and teaching programming to make the world a better place.

Create and customize radio buttons in React Native

6 min read 1914

Create and Customize Radio Buttons in React Native

Radio button elements are crucial when it comes to letting the client choose between multiple options. For example, assume that you own a successful app and want to get the user’s theme preferences (for dark and light mode). In this case, it would be sensible to display all available options in a radio button group.

A notorious use-case for radio group usage is Google’s search settings:

Google Radio Button Example

In this guide, you will learn how to build a radio button form using the React Native library. Furthermore, we will also be writing some code to style our radio elements.

This will be the outcome:

Radio Button Demo

We’ll be covering these topics:

Getting Started

Before writing some code, we need to first initialize our app repository. To scaffold a React Native project using Expo, execute this Bash command:

expo init radio-button-tutorial

Next, create a components folder in the root of your project directory. In this folder, we will store our custom React modules. This will help in code organization:

#in your project dir
mkdir components

In the end, your project folder structure should look like so:



Radio Button Folder Structure

Creating our radio button

Setting up our radio button component

In this part of the article, we will write some code to display a list of the user’s available choices.

First, navigate to your components folder. There, create a file called RadioButton.js.

In the RadioButton.js file, write the following snippet:

import React from 'react';
import { View, Text } from 'react-native';

export default function RadioButton({ data, onSelect }) {
  return (
    <View>
      {data.map((item) => {
        return <Text> {item.value}</Text>;
      })}
    </View>
  );
}

A few inferences from this code:

  • The RadioButton module will accept two props: data and onSelect. Here, data will be our array of user options. Moreover, onSelect will be a handler function that will run if the user makes a selection
  • Later on, we used the map function on our data array
  • The map method will help us display the value field of each item in the array

Let’s test it out!

In App.js, replace all the code with the following:

import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import RadioButton from './components/RadioButton';
export default function App() {
  const data = [
    { value: 'Apple' },
    { value: 'Samsung' },
    { value: 'Blackberry' },
  ];
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>Choose your favorite company: </Text>
      <RadioButton data={data} />
    </View>
  );
}

In the above code, we created an array called data. This variable contains the user’s list of choices. Later on, we passed in this variable into the data prop of the RadioButton component. As a result, this will render our list.

Radio Button List

Making items clickable and displaying user input

In this section, we will use React Native’s Pressable API to make our list interactive.

To do so, go to RadioButton.js and modify the return block to the following:

import {Pressable} from 'react-native'; //additional import.
//code to change of 'return' block in RadioButton.js
return (
  <View>
    {data.map((item) => {
      return (
        <Pressable onPress={() => alert("Your choice: " + item.value)}> {/* onPress handler runs when item is clicked.*/}
          <Text> {item.value}</Text>
        </Pressable>
      );
    })}
  </View>
);

In this code, we used the Pressable component to tell React Native that if the user taps on any item, it should display the user’s selection in a separate popup window.


More great articles from LogRocket:


Radio Button Popup

Building radio button functionality

In the RadioButton.js file, append the following snippet:

import { useState } from "react";

const [userOption, setUserOption] = useState(null);

return (
  <View>
    {data.map((item) => {
      return (
        /*Change the 'onPress' handler here */
        <Pressable onPress={() => setUserOption(item.value)}>
          <Text> {item.value}</Text>
        </Pressable>
      );
    })}
    <Text> User option: {userOption}</Text>
  </View>
);

Here’s a breakdown of this block:

  • First, declare a userOption Hook. This will store the user’s current selection. Its initial value will be null
  • Later on, use the onPress handler to tell React to update the value of userOption to the user’s current choice
  • In the end, display the value of userOption

Radio Button Displays User Option

Customizing our radio button

Here, our plan is to use the StyleSheet API to decorate our radio form. This will help in improving our app’s user experience.

To make this possible, in your components folder and create a new file called styles.js. Here, write the following code:

import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
  option: {
    fontSize: 20,
    color: 'white',
    textAlign: 'center',
  },
  unselected: {
    backgroundColor: 'red',
    margin: 5,
  },
  selected: {
    backgroundColor: 'blue',
    margin: 6,
    padding: 10,
    borderRadius: 10,
  },
});
export default styles;

Here’s a brief explanation:

  • The option property will be responsible for styling the text that displays the user’s options. Here, we are increasing its font size and changing its color and alignment values
  • As the name suggests, unselected will decorate the elements that are not selected. Here, we are modifying its background color
  • The selected style will be applied on the item that the user has chosen. In this case, we are changing its padding and using the borderRadius property to round the element’s borders

When that’s done, it’s now time to apply our style.

To do so, write this piece of code in RadioButton.js:

//code to change in 'return' block
data.map((item) => {
  return (
    <Pressable
      style={ //Line 5
        item.value === userOption ? styles.selected : styles.unselected
      } /*Add style here */ //Line 7
      onPress={() => setUserOption(item.value)}
    >
      {/* add style here */}
      <Text style={styles.option}> {item.value}</Text>
    </Pressable>
  );
});

Notice that in lines 5–7, we are first checking whether the user has clicked on a particular element. If this condition is met, React Native will use the selected style.

Otherwise, the unselected style will be applied.

Radio Button Selected Style

Using our onSelect handler

In RadioButton.js, edit your code like so:

//extra code removed for brevity.
const selectHandler = (value) => {
  onSelect(value);
  setUserOption(value);
};

return (
  <View>
    {data.map((item) => {
      return (
        <Pressable onPress={() => selectHandler(item.value)}>
        {/* Further code... */}
        <Text> User option: {userOption}</Text> {/* remove this line */} 

Here, notice that we have changed the onPress handler to run the selectHandler function. As a result, this will run the onSelect method and update the value of the userOption state.

It’s now time to use our custom handler function. To do so, navigate back to App.js and append this block:

import { useState } from "react";

const [option, setOption] = useState(null);
return (
  <View style={styles.container}>
    <Text style={styles.paragraph}>Choose your favorite company: </Text>
    {/* add 'onSelect' handler */}
    <RadioButton data={data} onSelect={(value) => setOption(value)} />
    <Text> Your option: {option}</Text>
  </View>
);

In this piece of code, we first declared an option state. Later on, we used the onSelect hook to tell React to update the value of option if the user taps on any item. In the end, React will display the value of option to the UI.

Radio Button Final Example

Congrats! You’ve now built a custom radio button!

In the end, your RadioButton.js file should look like this:

import React, { useState } from 'react';
import { View, Text, Pressable } from 'react-native';
import styles from './styles';

export default function RadioButton({ data, onSelect }) {
  const [userOption, setUserOption] = useState(null);
  const selectHandler = (value) => {
    onSelect(value);
    setUserOption(value);
  };
  return (
    <View>
      {data.map((item) => {
        return (
          <Pressable
            style={
              item.value === userOption ? styles.selected : styles.unselected
            }
            onPress={() => selectHandler(item.value)}>
            <Text style={styles.option}> {item.value}</Text>
          </Pressable>
        );
      })}
    </View>
  );
}

And App.js should have this code:

import React, { useState } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import RadioButton from './components/RadioButton';

export default function App() {
  const [option, setOption] = useState(null);
  const data = [
    { value: 'Apple' },
    { value: 'Samsung' },
    { value: 'Blackberry' },
  ];
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>Choose your favorite company: </Text>
      <RadioButton data={data} onSelect={(value) => setOption(value)} />
      <Text> Your option: {option}</Text> 
    </View>
  );
}
const styles = StyleSheet.create({
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Alternatives

If you don’t want to build your own radio button solution, the React Native community offers pre-built radio components that allow for high customization.

react-native-simple-radio-button

To install this package in your project, use this terminal command:

npm i react-native-simple-radio-button 

This code sample renders a radio group via the react-native-simple-radio-button library:

import RadioForm from 'react-native-simple-radio-button';

export default function ReactSimpleButton() {
  const [chosenOption, setChosenOption] = useState('apple'); //will store our current user options
  const options = [
    { label: 'Apple', value: 'apple' },
    { label: 'Samsung', value: 'samsung' },
  ]; //create our options for radio group
  return (
    <View>
      <Text> {chosenOption}</Text>
      <RadioForm
        radio_props={options}
        initial={0} //initial value of this group
        onPress={(value) => {
          setChosenOption(value);
        }} //if the user changes options, set the new value
      />
    </View>
  );
}

react-native-simple-radio-button

react-native-radio-buttons-group

You can incorporate radio-buttons-group in your app via npm or Yarn like so:

npm i react-native-radio-buttons

To draw a radio button group using this module, write this block of code:

import RadioGroup from 'react-native-radio-buttons-group';
export default function App() {
  //create our options
  const radioButtonsData = [
    {
      id: '1', // acts as primary key, should be unique and non-empty string
      label: 'Apple',
      value: 'apple',
    },
    {
      id: '2',
      label: 'Samsung',
      value: 'samsung',
    },
  ];
  const [radioButtons, setRadioButtons] = useState('apple'); //pass in our data to this state. This will store the current user's choice
  const setValue = (value) => {
    var newArray = value.filter((item)=>item.selected===true); //get the items that are selected
    setRadioButtons(newArray[0].value); //set the selected value in this Hook
  };
  return (
    <View>
      {/* The onPress handler tells React to change the value of the radioButtons Hook*/}
      <RadioGroup
        radioButtons={radioButtonsData} //pass in our array
        onPress={(value) => setValue(value)}
      />
      <Text>{radioButtons}</Text> {/*Display the value of the current user choice */}
    </View>
  );
}

react-native-radio-buttons-group

Using React Native Paper

React Native Paper is one of the most widely used component libraries in the React Native ecosystem. Other than radio buttons, they provide appbars, badges, and more.

The following terminal command will install React Native Paper for your project:

npm install react-native-paper

To display a couple of simple radio buttons:

import { RadioButton } from 'react-native-paper';

export default function ReactPaper() {
  const [checked, setChecked] = React.useState('Apple'); //initial choice
  return (
    <View>
    {/*Create first radio button */}
      <RadioButton
        value="Apple" 
        status={ checked === 'Apple' ? 'checked' : 'unchecked' } //if the value of checked is Apple, then select this button
        onPress={() => setChecked('Apple')} //when pressed, set the value of the checked Hook to 'Apple'
      />
      <RadioButton
        value="Samsung"
        status={ checked === 'Samsung' ? 'checked' : 'unchecked' }
        onPress={() => setChecked('Samsung')}
      />
      <Text> {checked}</Text>
    </View>
  );
};

React Native Paper radio button

Conclusion

You can access this project’s Expo Snack here.

In this article, you learned how to build a custom radio button in React Native that not only looks good, but is also extremely fast and stable. Don’t want to build your own radio element? No problem! You can use the SegmentedControl library or even React Native Paper’s RadioButton component. They are great alternatives that help you get up and running in a short span of time.

Thank you for reading!

: Full visibility into your web and mobile apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

LogRocket: Instantly recreate issues in your React Native apps.

LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your React Native apps — .

.
Hussain Arif Hussain is a CS student in Pakistan whose biggest interest is learning and teaching programming to make the world a better place.

Leave a Reply