Kitavi Joseph React Native Developer

Understanding React Native linear gradient

6 min read 1696

Gradients allow you to show more than one color with a smooth transition between the colors (think Instagram logo). They come in handy when trying to create multi-color backgrounds or custom buttons. You can have gradients in different varieties, horizontally, vertically, diagonally, etc. In this article, we’ll look at linear gradients and how to add them to our React Native apps.

Prerequisites

To follow along with this article, you should have:

  • A basic understanding of React Native
  • React Native set up on your development machine

Getting started

For this walkthrough, we will use the React Native community-recommended library for adding gradients into our application, the react-native-linear-gradient.

First, we’ll set up our new React Native project:

npx react-native init LinearGradientExample

cd LinearGradientExample
yarn start

Then, run our app to display the React Native welcome screen on a device or simulator.

With our React Native app running we can now add react-native-linear-gradient.

The set up for this varies depending on which React Native version you’re on, I’ll be using v0.6+ if you’re working on an older version of react-native check out the set up here:

yarn add react-native-linear-gradient

To finish up the setup, for iOS specifically, install pods:

npx pod-install

Linear gradients

As always, we’ll start off by importing the LinearGradient component from the library:

import LinearGradient from 'react-native-linear-gradient'

This component takes in a few props which determine how the gradient will be displayed, including colors, where to start, and where to end. Let’s break down and understand the props first before we can start using them to build our fancy gradients:

We made a custom demo for .
No really. Click here to check it out.

  • colors (Required)

    This is how we pass the colors we want to be displayed, colors can be passed in a different format, name, rgba, hex etc. The colors should be ordered the way we want them to be displayed. eg. colors={[ “purple”, “white” ]} the gradient will move from purple to white

  • start

    This is used to indicate where the gradient will start by passing coordinates for the x and y-axis. The coordinates are passed as a fraction of the whole view with values ranging from 0 – 1. The default is { x: 0.5, y: 0 } starting from the top center

  • end

    This is similar to start but indicates where the gradient finishes off at. It takes in coordinates just like start, which as mentioned earlier, is a fraction of the whole view. The default is { x: 0.5, y: 1 } ending at the bottom center

  • locations

    An array of numbers that define where each color will stop in the gradient. These values are also passed as a fraction of the entire gradient from 0 – 1 and have to map the corresponding colors passed in length and position. For colors={[“red”, “yellow”, “green”}] then we’ll have locations={[0, 0.5, 0.6]} with first color (red) covering 0 – 0.5, second (yellow) going from 0.5 – 0.6 and yellow 0.6 – 1

With that covered, let’s try and build out some gradients.

Vertical gradients

As mentioned earlier you can have your gradient in different orientations, let’s try vertical gradient which is default one first. The gradient starts from the top center going all the way down to bottom center. Let’s try that out.

Clear everything on App.js so we can start from the ground up. Add the following then we’ll break it down:

import React from 'react'
import { StyleSheet, View, Text } from 'react-native'
import LinearGradient from 'react-native-linear-gradient'. // import LinearGradient

class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <LinearGradient
          colors={['red', 'yellow', 'green' ]}
          style={styles.linearGradient}
        >
          <Text>Vertical Gradient</Text>
        </LinearGradient>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  linearGradient: {
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 5,
    height: 200,
    width: 350,
  },
})
export default App

Starting from the imports at the top, we import React from react, import a few components from react-native and add the import for LinearGradient.

Then we add a View with styling to position everything at the center, where we’ll add our gradient. In the LinearGradient component, we pass colors which is the required prop as mentioned earlier. We are adding three colors, so the gradient will move from red to yellow then green. By default, this will move from top center to bottom center.

Reload the app and we should be able to see our gradient:

react native vertical gradient background

Nice, our gradient is showing as expected.

Now, let’s play around a little bit with the gradient we currently have to better understand the props we talked about earlier.

As mentioned, the default properties for start={{ x: 0.5, y: 0 }} which means the gradient will start from the top center, but what do we mean by top center? Imagine the entire width of the gradient ie. x-axis is calibrated from 0 – 1, the center should be 0.5 as shown below. So altering that value should shift what point at the top our gradient starts from creating a diagonal gradient.

Let’s do that. Update our current LinearGradient to add values for start as shown below:

...
      <LinearGradient
        colors={['red', 'yellow', 'green' ]}
        style={styles.linearGradient}
        start={{ x: 0.7, y: 0 }}
      >
        <Text>Diagonal Gradient</Text>
      </LinearGradient>
...

Diagonal gradient

As you can see in the screenshot above the gradient becomes diagonal, starting somewhere between 0.5 and 1 going downwards. If you have the value as either 0 or 1 the diagonal gradient will start at the respective corners, right or left.

Adjusting the y-axis value will determine where the gradient will start. The space before the gradient will be covered by the first color, updating the props to start={{ x: 0.5, y: 0.5}} will have the gradient start at the center of our view, with the top half covered by red, like this:

vertical gradient with more red

Horizontal gradient

Now that we understand how to update our starting point on both the x and y-axis, let’s combine that with the end property to create horizontal gradients.

As discussed earlier, end determines where our gradient will end at. So ideally for a horizontal gradient, we’d want it to start left center and end at right center.

Let’s try that out:

...
      <LinearGradient
        colors={['red', 'yellow', 'green' ]}
        style={styles.linearGradient}
        start={{ x: 0, y: 0.5 }}
        end={{ x: 1, y: 0.5 }}
      >
        <Text>Horizontal Gradient</Text>
      </LinearGradient>
...

As you can see, the y-axis is maintained from start to end, whereas the x-axis moves from 0 – 1 creating the following gradient:
horizontal gradientWe can further adjust this to create a diagonal gradient close to the horizontal alignment. Updating start={{ x: 0, y: 0 }} and end={{ x: 1, y: 1 }} should create a gradient like this:

diagonalgradient

Locations

With most of the other props put into use, we only have the location prop pending that we haven’t utilized yet. Let’s change that.

Just a quick recap, locations determines where a color will stop in the gradient and have to map up to the corresponding color values.

Locations is mostly used when you want one or more colors to cover more space in the gradient view in comparison to the others. The color with the larger range as indicated earlier will cover more space:

...
      <LinearGradient
        colors={['red', 'yellow', 'green' ]}
        style={styles.linearGradient}
        start={{ x: 0, y: 0.5 }}
        end={{ x: 1, y: 0.5 }}
        locations={[0, 0.7, 0.9]}
      >
        <Text>H. Location Gradient</Text>
      </LinearGradient>
      <LinearGradient
        colors={['red', 'yellow', 'green' ]}
        style={styles.linearGradient}
        locations={[0, 0.3, 0.9]}
      >
        <Text>V. Location Gradient</Text>
      </LinearGradient>
...

Let’s see that in action:
h. location gradient

v location gradient

Feel free to play around with the colors, change them, add more, adjust the values for start, end, and locations and see how they behave.

Bonus

In this section, we are going to see a few use cases for LinearGradients covered above. We’ll create a few things here just to get you going:

  • Full-screen multi-colour background
  • Button with gradient background
  • Button with gradient border

For this let’s start fresh, create a new file called Home.js and update index.js to point to it as the root file:

// index.js
...
// import App from './App'  // comment this out
import App from './Home'  // add this
...

Now our app should render the Home screen so we can make the updates there.

Then let’s jump onto the new Home.js file and create a few things. First the full-screen multi-colour background:

// Home.js
import React from 'react'
import { StyleSheet, Text } from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
class Home extends React.Component {
  render() {
    return (
      <LinearGradient
        colors={['purple', 'white']}
        style={styles.container}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
      >
        <Text>Home Screen</Text>
      </LinearGradient>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
})
export default Home

You can choose whether or not to have the start and end props to create a vertical or diagonal background:

home screen purple gradient background

home screen gradient

Then finally for our two buttons, let’s jump back on Home.js just below the home screen text and add the two buttons. I’ve used horizontal backgrounds for both, the first one (gradient background) tries to mimic the Instagram color scheme where as the other one created a border gradient effect:

// Home.js

...
      <Text>Home Screen</Text>
      <TouchableOpacity onPress={() => {}}>
        <LinearGradient
          start={{ x: 0, y: 0 }}
          end={{x: 1, y: 1 }}
          colors={['#5851DB', '#C13584', '#E1306C', '#FD1D1D', '#F77737']}
          style={styles.instagramButton}
          >
          <Text style={{ color: 'white' }}>
            Sign In With Instagram
          </Text>
        </LinearGradient>
      </TouchableOpacity>
      <LinearGradient
        start={{ x: 0, y: 0 }}
        end={{x: 1, y: 1 }}
        colors={[ 'red', 'yellow', 'green' ]}
        style={{
          alignItems: 'center',
          justifyContent: 'center',
          borderRadius: 10,
        }}
      >
        <TouchableOpacity
          onPress={() => {}}
          style={styles.signUpButton}
        >
          <Text>Sign Up</Text>
        </TouchableOpacity>
      </LinearGradient>

...

// styles
  instagramButton: {
    paddingHorizontal: 40,
    paddingVertical: 10,
    borderRadius: 10,
    margin: 20
  },
  signUpButton: {
    margin: 1,
    width: 200,
    borderRadius: 10,
    paddingVertical: 10,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
  },

This should give us a final output as seen below:

react native home screen with instagram button

Conclusion

As always practice makes perfect, so play around with the different props until you have a hang of it.

A word of caution, when it comes to colors, try not to overdo them, having too many colors on your screen can adversely affect the user interface and experience.

Find the code for all the examples covered here on my GitHub.

: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Kitavi Joseph React Native Developer

Leave a Reply