How to create Gradient Text in React Native
Gradient text is a great way to add visual interest and depth to your mobile app. It helps to make your text stand out and draw the user’s attention. In this blog post, let’s learn how to add gradient Text in react native.
For this you need two libraries- react native linear gradient and react native masked view. The react native linear gradient helps to create gradients and the masked view library renders a masked view.
We can combine features of both libraries to create gradient text in react native.
If you are using React Native CLI then install both libraries using the following commands.
yarn add react-native-linear-gradient
yarn add @react-native-masked-view/masked-view
And also run pod install for iOS devices.
npx pod-install
Then you can import libraries as given below.
import LinearGradient from 'react-native-linear-gradient';
import MaskedView from '@react-native-masked-view/masked-view';
That’s it for react native CLI users.
If you are using react native expo then execute the following commands to add libraries.
npx expo install expo-linear-gradient
npx expo install @react-native-masked-view/masked-view
You can import them as given below.
import { LinearGradient } from 'expo-linear-gradient';
import MaskedView from '@react-native-masked-view/masked-view';
That’s the installation part.
First, you have to create a GedientText component as given below.
import React from 'react';
import {Text} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import MaskedView from '@react-native-masked-view/masked-view';
const GradientText = props => {
return (
<MaskedView maskElement={<Text {...props} />}>
<LinearGradient
colors={['red', 'green', 'blue']}
start={{x: 0, y: 0}}
end={{x: 1, y: 0}}>
<Text {...props} style={[props.style, {opacity: 0}]} />
</LinearGradient>
</MaskedView>
);
};
export default GradientText;
Now, just import the component and use it as follows.
import React from 'react';
import {View, StyleSheet} from 'react-native';
import GradientText from './GradientText';
const App = () => {
return (
<View style={styles.container}>
<GradientText style={styles.text}>Hello world</GradientText>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 30,
},
});
export default App;
Then you will get the following output.
That’s how you add gradient text easily in react native.