Introduction :
In this post, I will show you how to place two buttons side by side in react native. We will create one new component for the buttons.
React native project :
Let’s create one starter react native project. Create one new file CButton.js with the below code :
import React from "react";
import { TouchableOpacity, Text, StyleSheet } from "react-native";
const CButton = ({ text }) => {
return (
<TouchableOpacity style={styles.button}>
<Text style={styles.text}>{text}</Text>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
button: {
backgroundColor: "blue",
padding: 18,
width: "46%",
height: 60,
},
text: {
fontSize: 18,
color: "white",
textAlign: "center",
},
});
export default CButton;
We are using TouchableOpacity for the button. One Text component is added for showing the title. text is passed to this component.
width is 46%,and height is 60. You can change these values to see how it looks.
For simplicity, we are not adding any click listener here. If you want, you can pass one with text.
Now, let’s create our main component and add this button :
import React from "react";
import { SafeAreaView, StatusBar, StyleSheet, View } from "react-native";
import CButton from "./CButton";
const App = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView style={styles.container}>
<View style={styles.parent}>
<CButton text={"Button one"} />
<CButton text={"Button two"} />
</View>
</SafeAreaView>
</>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
parent: {
flex: 1,
flexDirection: "row",
justifyContent: "space-around",
},
});
export default App;
Here, we are adding two CButton with different text values.
The wrapper View of these buttons is having flex = 1 with flexDirection = row and justifyContent as space-around. space-around adds paddings of the buttons on each side.
Run it, and it will give one output as like below :
And horizontally :
You might also like:
- React native example to create Text with different colors or multicolored Text
- How to remove yellow warning box in React Native
- How to hide the keyboard on touch outside in react native
- Handling keyboard with react-native ScrollView
- How to show pdf files in react native applications
- How to add scroll to top to a FlatList in ReactNative app
- How to change the background color of a View dynamically in React Native