Linear gradient for border color in React Native
This week I started a new project at work. While I was studying the design I knew it will be kind of hard to implement the linear gradient that Andrei, my colleague designed (btw, thanks for suggesting me what I am about to detail here).
The design is pretty simple to implement if you want to border only the top or the bottom of a input field. But I had to implement it on a button that looks like this:
React Native doesn’t allow you to do that, neither the react-native-linear-gradient
package. As Andrei suggested, we need a workaround for this.
Let’s start by creating a new button:
<TouchableOpacity
onPress={() => {})}
style={styles.buttonContainer}
>
<Text style={style.buttonText}>Login</Text>
</TouchableOpacity>
Styles:
buttonContainer: {
width: 200,
alignItems: 'center',
},
buttonText: {
textAlign: 'center',
color: '#4C64FF',
padding: 15,
width: 200
}
Right now the button will be simple. No background, only the Text rendered. A simple 200 pixel width button.
Our method will nest this button on top of a linear gradient container that we will create next:
Start by installing the react-native-linear-gradient
package. Let’s create a 200px container:
<LinearGradient
colors={['#00FFFF', '#17C8FF', '#329BFF', '#4C64FF', '#6536FF', '#8000FF']}
start={{x: 0.0, y: 1.0}} end={{x: 1.0, y: 1.0}}
style={{ height: 48, width: 200, alignItems: 'center', justifyContent: 'center', width: 200}}
>
</LinearGradient>
You should see this if you followed the steps above:
We just need to nest the button we created above, into the LinearGradient component and we should be pretty much done:
<LinearGradient
colors={['#00FFFF', '#17C8FF', '#329BFF', '#4C64FF', '#6536FF', '#8000FF']}
start={{x: 0.0, y: 1.0}} end={{x: 1.0, y: 1.0}}
style={{ height: 48, width: 200, alignItems: 'center', justifyContent: 'center', width: 200}}
>
<TouchableOpacity style={styles.buttonContainer}>
<Text style={styles.buttonText}>
LOGIN
</Text>
</TouchableOpacity>
</LinearGradient>
So right now the upper and lower border are basically rendered using the gradient we defined (REMEMBER: you need to calculate the padding for the Text
component. That depends by text size, font weight, etc …). As we can see the left and right borders are still white. That’s because the width of the TouchableOpacity
component is the same as the LinearGradient
one.
We need to reduce the width by 2px (one for each side) and add margin for left and right:
buttonText: {
textAlign: 'center',
color: '#4C64FF',
padding: 15,
marginLeft: 1,
marginRight: 1,
width: 198
}
This will give us a great gradient for the button we want:
For the moment, Expo cannot be embedded here so here’s the link to the final project: https://snack.expo.io/rJT765kR-. Maybe Medium will solve this in the future.
You can use this technique for basically any gradient border you want.