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-web
template, 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
FullWidthImage
insteadImage
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
heroHeaderText
components withheroHeaderContainer
in order to position both components simultaneously -
heroContainer
will haveposition: relative
, this will allow any children components that have aposition: absolute
to useheroContainer
as a reference point, in this case, we are addingposition: absolute
to theheroHeaderContainer
, (note: even though we do not need to addposition: relative
to work, but if there are parent elements of
Step 3, Add Linear Gradient
- To make the
heroHeaderText
more 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-gradient
because we are using thereact-native-web
template on codesandbox, forreact-native
apps, please use react-native-linear-gradient - Use
position: absolute
andzIndex
to position the linear gradient on top of theHero Banner
image
Step 4, Add A heroSubheader
- To add more "flare" to our awesome hero banner, we will add a hero subheader using the
Button
component fromreact-native
Finished,
Top comments (0)