Add linear gradient in React Native using Expo

AverageTechie
2 min readJun 22, 2022

--

First lets install the linear gradient using expo

expo install expo-linear-gradient

Installation :

expo-linear-gradient installation

Once the installation is complete, import the linear gradient to your file.

import { LinearGradient } from 'expo-linear-gradient';

If you see an error in the console window something like this:

InternalError Metro has encountered an error: While trying to resolve module `expo-linear-gradient` from file `<path to root dir>\App.js`, the package `<path to root dir>\node_modules\expo-linear-gradient\package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`<path to root dir>\node_modules\expo-linear-gradient\build\LinearGradient.js`. Indeed, none of these files exist:

MetroJS bundler default does not compile typescript .ts and .tsx extension files. We need tell MetroJS bundler to compile .ts and .tsx files. Solved this error by editing/adding a metro.config.js file in root project folder.

We will create a ne metro.config.js file and place in the root directory of our project.

metro.config.js

module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
resolver: {
sourceExts: ['jsx', 'js', 'ts', 'tsx'], //add here
},
};

Add the above file and restart the application.

Now, update your view:

export default function App() {return (<LinearGradient colors={['#4e0328', '#ddb52f']} style={styles.rootContainer}><View><Text>Hello</Text></View></LinearGradient>);}

In the colors attribute we can give all colors that we want in a gradient. It can be more than two, not aware about the upper limit as of now. Need to check the documentation.

This is how it would look like:

Gradient in React Native

Hope, this helped :)

--

--

AverageTechie
AverageTechie

Written by AverageTechie

Java | Microservices | Reactive Programming | React JS | Kafka | No SQL | AWS | Docker | k8s | Hands on

No responses yet