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

5 min read 1449

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

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

We made a custom demo for .
No really. Click here to check it out.

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.

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',
  },
});

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 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 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