React-Native styling using CSS stylesheets and class names

Viewed 26283

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;
}
4 Answers

The object that the documentation is referring to is the StyleSheet object in JSX. You need to import StyleSheet from react-native. The style that you have written to a const variable here will go into that object which you will create using StyleSheet.

import {StyleSheet} from 'react-native';
var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'space-evenly',
    backgroundColor: '#0070af',
    alignItems: 'center',
    backgroundColor:'#0070af'
  },
  textstyle:{
    color:'white',
    fontFamily: "Roboto",
  }});

export default styles;

need to config react native sass /css transformer https://github.com/kristerkari/react-native-sass-transformer

Transform JSX className property to a style property that calculates styles at runtime in React Native. The plugin is used to match style objects containing parsed CSS media queries and CSS viewport units with React Native.

Please check out this link : https://github.com/kristerkari/babel-plugin-react-native-classname-to-dynamic-style

When using React native typescript, you need to install this package also https://github.com/kristerkari/react-native-types-for-css-modules

Related