React Native – Linear Gradient
This is an example of a Linear Gradient Component in React Native. A Gradients let you display smooth transitions between two or more specified colors. The gradient can be of two types:
- Linear Gradients (goes down/up/left/right/diagonally)
- Radial Gradients (defined by their center)
In this example, we will see the Linear Gradient. To Make a Linear Gradient in React Native we will use the LinearGradient component from @react-native-community/react-native-linear-gradient provided by react-native-community.
Additional props
In addition to regular View
props, you can also provide additional props to customize your gradient look:
colors
An array of at least two color values that represent gradient colors. Example: ['red', 'blue']
sets gradient from red to blue.
start
An optional object of the following type: { x: number, y: number }
. Coordinates declare the position that the gradient starts at, as a fraction of the overall size of the gradient, starting from the top left corner. Example: { x: 0.1, y: 0.1 }
means that the gradient will start 10% from the top and 10% from the left.
end
Same as start, but for the end of the gradient.
locations
An optional array of numbers defining the location of each gradient color stop, mapping to the color with the same index in colors
 prop. Example: [0.1, 0.75, 1]
 means that first color will take 0% – 10%, second color will take 10% – 75% and finally third color will occupy 75% – 100%.
First we will install the dependency
npm install react-native-linear-gradient --save
//Link the dependency
react-native link react-native-linear-gradient
App.js Code
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
{/*Simple Gradient*/}
<LinearGradient
colors={['#ffd700', '#ffff00']}
style={styles.linearGradient}>
<Text style={styles.buttonText}>
Simple Linear Gradient Backgrount
</Text>
</LinearGradient>
{/*Horizontal Gradient*/}
<LinearGradient
start={{x: 0, y: 0}}
end={{x: 1, y: 0}}
colors={['#ffd700', '#ffff00']}
style={styles.linearGradient}>
<Text style={styles.buttonText}>
Horizontal Gradient Backgrount
</Text>
</LinearGradient>
{/*Location Gradient*/}
<LinearGradient
start={{x: 0.0, y: 0.25}}
end={{x: 0.5, y: 1.0}}
locations={[0,0.5,0.6]}
colors={['#ffd700', '#ffff00','#eedd82']}
style={styles.linearGradient}>
<Text style={styles.buttonText}>
Location Gradient Backgrount
</Text>
</LinearGradient>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
linearGradient: {
paddingLeft: 15,
paddingRight: 15,
borderRadius: 5,
marginTop:16,
width:350,
},
buttonText: {
fontSize: 18,
fontFamily: 'Gill Sans',
textAlign: 'center',
margin: 10,
color: '#ffffff',
backgroundColor: 'transparent',
},
});