Introduction :
This tutorial is to show you how we can create circular buttons in React Native. I will use TouchableOpacity for the button. Also, I will create this button as a separate component that can be used by passing different props values.
React native program :
Create one starter react native project and update its App.js file as below :
import React from 'react';
import {StyleSheet, Text, View, TouchableOpacity, Alert} from 'react-native';
const CircleButton = props => (
<TouchableOpacity
style={{
margin: props.margin,
height: props.size,
width: props.size,
backgroundColor: props.color,
alignItems: 'center',
justifyContent: 'center',
borderRadius: props.size * 2,
}}
onPress={props.onPress}>
<Text style={{color: props.textColor, fontSize: props.fontSize}}>
{props.text}
</Text>
</TouchableOpacity>
);
export default function ExampleProgram() {
const showMessage = () => Alert.alert('Button clicked !');
return (
<View style={styles.container}>
<CircleButton
text="Btn-1"
size={150}
color="#7986cb"
textColor="white"
fontSize={20}
margin={10}
onPress={showMessage}
/>
<CircleButton
text="Btn-2"
size={100}
color="#9c27b0"
textColor="white"
margin={10}
fontSize={20}
/>
<CircleButton
text="Btn-3"
size={200}
color="#2196f3"
textColor="white"
margin={10}
fontSize={20}
/>
<CircleButton
text="Btn-4"
size={80}
color="#00bcd4"
textColor="white"
margin={10}
fontSize={20}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
margin: 12,
},
});
Explanation :
-
Here, we have created one component called CircleButton to create a circle button view.
-
It uses one TouchableOpacity with a text inside.
-
The height and width are of equal size and borderRadius is twice the size of height/width.
-
It assigns the values from the provided props
-
Make sure to set alignItems and justifyContent as center to put the text in middle of the TouchableOpacity view.
You can put CircleButton component in a separate file and export it from there.
Output :
It will give the below output :