How to apply react-native-linear-gradient for the entire app background with React Native

Viewed 917

I'm working on a React Native app. I can get the results I want by wrapping every single one of my container components in something like this:

    <LinearGradient
      style={{ flex: 1 }}
      colors={[primary, primaryGradient2, primaryGradient1]}
      locations={locations}
    >
        <ContentHere></ContentHere>
    </LinearGradient>

What I would like to do is keep my project DRY and not have to repeat doing this for every container level component.

I tried making a component that returns the LinearGradient with the proper config I'd like based off a theme object, something like this:

<GradientTheme theme={theme}>
  <MainContainer>Stuff here </MainContainer>
</ GradientTheme>

However, this renders without any of the MainContainer elements at all. The code for GradientTheme is as follows:

import React from 'react';
import PropTypes from 'prop-types';
import LinearGradient from 'react-native-linear-gradient';

export const GradientTheme = ({ theme }) => {

const { primary, primaryGradient2, primaryGradient1, locations } = 
theme;
    return (
        <LinearGradient
            style={{ flex: 1 }}
            colors={[primary, primaryGradient2, primaryGradient1]}
            locations={locations}
        />
    );
};

GradientTheme.propTypes = {
    theme: PropTypes.object
};

Just some extra info, I'm also using React-Navigation. A more ideal solution would be having a global way to apply all of this styling and theming.

1 Answers

However, this renders without any of the MainContainer elements at all.

You need to use this.props.children

<LinearGradient
  style={{ flex: 1 }}
  colors={[primary, primaryGradient2, primaryGradient1]}
  locations={locations}>
  //add this:
  {this.props.children}
</LinearGradient>

It's a prop passed to all components using an opening and closing tag and contains whatever is between the opening and closing tags.

I'm not totally clear on exactly what you're trying to accomplish, but I suspect you would be best served by placing the <GradientTheme/> component at or near the root of your app, and managing the theme either locally in it's parent component state or with redux. In case you need it, here is a nice series of tutorials on using redux and react-navigation together in react-native.

Related