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

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay