How to Convert View into Custom Shapes like Square, Rectangle, Circle and Triangle
A View is the most fundamental component for building the user interface of a React Native mobile app. The View acts as a container and it can have any number of children. In this blog post, let’s check how to convert or show View components as different custom shapes such as square, rectangle, circle, triangle, etc.
We can convert Views into custom shapes by changing the style. Tuning the style props such as height, width, borderRadius, etc helps you to achieve the desired shape.
The height and width should be the same to achieve the shape of a square.
square: {
width: 80,
height: 80,
backgroundColor: 'red',
}
In the case of a rectangle, the width should be double the height.
rectangle: {
width: 80 * 2,
height: 80,
backgroundColor: "blue",
}
With the height and width made the same, the border-radius should be half of either height or width.
circle: {
width: 80,
height: 80,
borderRadius: 80 / 2,
backgroundColor: "orange"
}
Getting the shape of a triangle is a bit tricky.
triangle: {
width: 0,
height: 0,
borderLeftWidth: 50,
borderRightWidth: 50,
borderBottomWidth: 100,
borderStyle: 'solid',
borderBottomColor: 'green',
backgroundColor: 'transparent',
borderLeftColor: 'transparent',
borderRightColor: 'transparent'
}
Following is the full code of the react native custom shape example:
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<Text style={styles.header}> Square </Text>
<View style={styles.square} />
<Text style={styles.header}> Rectangle </Text>
<View style={styles.rectangle} />
<Text style={styles.header}> Circle </Text>
<View style={styles.circle} />
<Text style={styles.header}> Triangle </Text>
<View style={styles.triangle} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
},
header: {
fontSize: 16,
marginTop: 20,
},
square: {
width: 80,
height: 80,
backgroundColor: 'red',
},
rectangle: {
width: 80 * 2,
height: 80,
backgroundColor: 'blue',
},
circle: {
width: 80,
height: 80,
borderRadius: 80 / 2,
backgroundColor: 'orange',
},
triangle: {
width: 0,
height: 0,
borderLeftWidth: 50,
borderRightWidth: 50,
borderBottomWidth: 100,
borderStyle: 'solid',
borderBottomColor: 'green',
backgroundColor: 'transparent',
borderLeftColor: 'transparent',
borderRightColor: 'transparent',
},
});
export default App;
Following is the screenshot of the output:
That’s how you add custom shapes with View in react native.