How can you pass styles through to a container component in React-Native

I found a way to do it while browsing through the source code for React-Native-Router-Flux.

Stylesheets can be passed in as an array, and it looks like React-Native applies them in order from left to right (allowing you to overwrite specific properties).

Here is what the updated MyText component should look like:

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

const styles = StyleSheet.create({text: {color: 'orange', fontSize: 14, fontWeight: 'bold'}});

export default class MyText extends Component {
    render() {
        return <Text style={[styles.text, this.props.style]}>{this.props.children}</Text>
    }
}

Using typescript and functional components:

type CustomProps = {
   text: string,
   onPress: () => void,
   style?: {}
};

 const CustomButton = ({ style, text, onPress }: CustomProps) => {
   return (
    <TouchableOpacity
        style={[styles.container, style]}
        onPress={onPress}>

        <Text style={styles.text}>{text}</Text>
    </TouchableOpacity>
)
};

 const styles = StyleSheet.create({
     container: {
         elevation: 8,
         backgroundColor: Colors.white,
     },
     text: {
         fontSize: 18,
         color: Colors.primary_dark,
         fontWeight: "bold",
         alignSelf: "center",
         textTransform: "uppercase",
         textAlign: "center"
     }
 });

Then use it like this:

<CustomButton style={{ backgroundColor: 'red'}} text="hi" onPress={() => {console.log('Hi'}}

Tags:

React Native