Use Linear Gradient npm library instead of absolute position style to have two colored background in react native

Sourajit Karada
2 min readMay 11, 2021

Have you ever got a design that has components with two different colored backgrounds? If yes, how did you try to get the design? Is it using position absolute styles?

Photo by Marcelo Cidrack on Unsplash

And colors play a major role in the design along with the placement of pieces. Don’t you feel the same after seeing the above picture? There are apps like Instagram, Facebook, Google, and a lot more that use gradient background. Fortunately, we have react-native-linear-gradient in the npm library. We can use that library to achieve the gradient background in react native.

Photo by Melvin Thambi on Unsplash

There are pretty good examples that are given in their Github link.

Let’s take an example given in their Github link.

The following code will produce something like this:

In the above code snippet, you can see the increase/decrease of color transparency to match the next color pattern in the colors prop. But what if you want two colors in the background like the image given below.

Here the background has two colors with 50% occupancy each.

To achieve this, you can go with multiple View components and using position absolute.

But if we use position absolute we have to check a lot of other style properties well. Sometimes it gets hectic to achieve. It becomes nasty when we try to share this component with another component. There has an easy solution to achieve this using a linear-gradient library.

The following code snippet can help you achieve the figure(a) design.

I have used locations prop to achieve. Check other props and linear-gradient library and try to manipulate things. I’m sure you will learn a lot from this.

--

--