Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 376
sflogen Avatar asked Apr 13 '16 20:04

sflogen


People also ask

What is style container in React Native?

With React Native, you style your application using JavaScript. All of the core components accept a prop named style . The style names and values usually match how CSS works on the web, except names are written using camel casing, e.g. backgroundColor rather than background-color .


1 Answers

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>
    }
}
like image 161
sflogen Avatar answered Sep 22 '22 06:09

sflogen