DEV Community

Matt Ruiz
Matt Ruiz

Posted on

Simple and Reusable React Native Radio Button

Image description

Creating the RadioButton.tsx component

import React from "react";
import {View, Text, SafeAreaView, StyleSheet, TouchableOpacity} from "react-native";

type Props = {
  isSelected: boolean;
  onPress: () => void;
};

export const RadioButton = (props: Props) => {
  const {isSelected, onPress} = props;

  return (
    <TouchableOpacity style={styles.outer} onPress={onPress}>
      {isSelected && <View style={styles.inner} />}
    </TouchableOpacity>
  )
};

const styles = StyleSheet.create({
  outer: {
    height: 24,
    width: 24,
    borderRadius: 12,
    borderWidth: 2,
    borderColor: "#000",
    alignItems: "center",
    justifyContent: "center",
  },
  inner: {
    height: 12,
    width: 12,
    borderRadius: 6,
    backgroundColor: "#000",
  },
});
Enter fullscreen mode Exit fullscreen mode

Here's an example of using the <RadioButton>:

import {registerRootComponent} from "expo";
import React from "react";
import {Text, SafeAreaView, StyleSheet} from "react-native";
import {RadioButton} from "./components/RadioButton";

const App = () => {
  const [isSelected, setIsSelected] = React.useState(false);

  return (
    <SafeAreaView>
      <Text style={styles.header}>Welcome to One Minute Coding!</Text>

      <RadioButton isSelected={isSelected} onPress={() => setIsSelected(true)} />
    </SafeAreaView>
  );
};

export default registerRootComponent(App);

const styles = StyleSheet.create({
  header: {
    fontSize: 24,
    fontWeight: "bold",
    textAlign: "center",
    height: 50,
    width: '100%',
  },
});
Enter fullscreen mode Exit fullscreen mode

Hope this helps! I would love to see how y'all make use of this - please share.

  • Matt

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more