Linear Gradient background color in React-Native

Viewed 34999

In my application I need to dynamically change the background color. The changes comes from the child view to the parent view through callback. Currently it looks like this:

Child view:

onButton1Press() {
 this.props.callbackFromParent('#ff4c00');
}

Parent view:

myCallback = (dataFromChild) => {
 this.setState({ backgroundColor: dataFromChild }); 
}

It's working great, but the problem is that I need to implement a linear gradient background color.

I found a 'react-native-linear-gradient' library, that works well on other views, like buttons, but I cannot to set it to the background color.

Example:

    <LinearGradient colors={['#085d87', '#27c7bb']}
       start={{ x: 0, y: 1 }}
       end={{ x: 1, y: 0 }}>
        <Text style={styles.buttonText}>LinearGradient</Text>
    </LinearGradient>

It is possible to set the background color to gradient? Is there another approach to make it possible in react-native? Thanks.

3 Answers

If you want to put it in background, then you only need to wrap the <LinearGradient with your view that is background Example:

<View style={{flex:1}}>
   <LinearGradient color={[...]} style={{flex:1}}>
    ...//Your component
   </LinearGradient>
</View> 

Hope this helps!

You can create a custom class or component and use this to change parent view when button pressed on child component.

Example code :

import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class Gradient extends Component {
  render() {
    const  gradientHeight=500;
    const gradientBackground  = 'purple';
    const data = Array.from({ length: gradientHeight });
      return (
          <View style={{flex:1,justifyContent:'center'}}>
              {data.map((_, i) => (
                  <View
                      key={i}
                      style={{
                          position: 'absolute',
                          backgroundColor: gradientBackground,
                          height: 1,
                          bottom: (gradientHeight - i),
                          right: 0,
                          left: 0,
                          zIndex: 2,
                          opacity: (1 / gradientHeight) * (i + 1)
                      }}
                  />
              ))}
              <Text style{{textAlign:'center',alignSelf:'center',fontSize:25}}>Hello</Text>
          </View>
      );
  }
}

Expo has LinearGradient, it is very easy.

import { LinearGradient } from 'expo';

<LinearGradient
   colors={['#4c669f', '#3b5998', '#192f6a']}
   style={{ padding: 15, alignItems: 'center', borderRadius: 5 }}>
     <Text
       style={{
         backgroundColor: 'transparent',
         fontSize: 15,
         color: '#fff',
       }}>
       Sign in with Facebook
     </Text>
   </LinearGradient>
Related