React-Native styling using CSS stylesheets and class names

rodiwa picture rodiwa · Aug 16, 2017 · Viewed 15.8k times · Source

I've just started working on a react-native app. The official docs suggest to use JavaScript objects to create styles for your components, like so,

<Text style={style.text}>Blah Blah</Text>
const style = {
    text: {
        fontSize: 20
    }
}

I'm trying to add a className to the Text property, so I can add css using simple stylesheets. Is this even possible with react-native (I know we can do this in react, though)? Something like this,

<Text className="text-style"></Text>

// from CSS file
text-style: {
    font-size: 20;
}

Answer

Tierna D. Jack Lawless picture Tierna D. Jack Lawless · Aug 16, 2017

The way React Native works with CSS styles is that the StyleSheet object is a js replica of CSS as a language. all you need to do is create a .js and import the js objects containing the StyleSheet objects.

an example of a StyleSheet JS object would be:

import { StyleSheet } from 'react-native'; 

const styles = StyleSheet.create({
  textStyle: {
    fontSize: 20,
  },
  otherStyle: {
    position: 'absolute',
    justifyContent: 'center',
  }
});

basically what it needs is an array of objects that follow the API of StyleSheet. A good rule of thumb is to write the css styles you know in camel case, e.g. justifyContent instead of justify-content the React Native engine does its best to replicate CSS through the use of these StyleSheet objects and reading documentation and examples will help you understand what StyleSheet is capable and not capable of(hint: flex and the Dimensions API are amazing and percentages are strings like '50%').