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

18,333

Solution 1

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>
    }
}

Solution 2

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'}}
Share:
18,333

Related videos on Youtube

sflogen
Author by

sflogen

Updated on September 15, 2022

Comments

  • sflogen
    sflogen over 1 year

    I'm trying to create some reusable UI components for my React-Native app that have default styles.

    An example default MyText (orange, 14, bold):

    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.children}</Text>
        }
    }
    

    How I would like to use it:

    import Text from '../ui/myText';
    
    ... 
    <Text style={{color: 'black'}}>My custom styled text, but in black instead of orange</Text>
    ...
    

    Is there a way to do this? Obviously if I try to access this.props.style it just returns an ID for a compiled stylesheet.