Today I would like to write a short tutorial on how to make a React Native hero banner that has a linear gradient layer.
Step 1, Make a banner image using FullWidthImage
- Create a project using codesandbox's
react-native-webtemplate, remove the unused components
import React, { Component } from "react";
import { Image, StyleSheet, View } from "react-native";
const logoUri =
"https://imagesvc.timeincapp.com/v3/fan/image?url=https://raptorsrapture.com/wp-content/uploads/getty-images/2016/04/1094224730.jpeg&w=1600";
class App extends Component {
render() {
return (
<View>
<Image
accessibilityLabel="React logo"
source={{ uri: logoUri }}
resizeMode="contain"
style={styles.heroHeaderImage}
/>
</View>
);
}
}
const styles = StyleSheet.create({
heroHeaderImage: {
height: 80
}
});
export default App;
The Problem
- we can only resize the image's width by controlling its height
Solution
- Use
FullWidthImageinsteadImage
FullWidthImage is a package that allows a responsive Image element that takes the full width of its parent element while maintaining aspect ratio.
It has a neat built-in feature called automatic detection, which can automatically detect the aspect ratio of remote images, all you need to provide is the uri as you would do with the regular Image component.
Which is what we are going to use.
Just like that, we have a hero banner.
Step 2, Add and Position HeroHeaderText
- Wrap the
heroHeaderTextcomponents withheroHeaderContainerin order to position both components simultaneously -
heroContainerwill haveposition: relative, this will allow any children components that have aposition: absoluteto useheroContaineras a reference point, in this case, we are addingposition: absoluteto theheroHeaderContainer, (note: even though we do not need to addposition: relativeto work, but if there are parent elements of
Step 3, Add Linear Gradient
- To make the
heroHeaderTextmore visible, one common practice is to add a linear gradient to the background image, the React Native approach of adding the linear gradient is different than how you would on the web we are usingreact-native-web-linear-gradientbecause we are using thereact-native-webtemplate on codesandbox, forreact-nativeapps, please use react-native-linear-gradient - Use
position: absoluteandzIndexto position the linear gradient on top of theHero Bannerimage
Step 4, Add A heroSubheader
- To add more "flare" to our awesome hero banner, we will add a hero subheader using the
Buttoncomponent fromreact-native
Finished,
Top comments (0)