Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native styling using CSS stylesheets and class names

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;
}
like image 974
rodiwa Avatar asked Aug 16 '17 09:08

rodiwa


2 Answers

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%').

like image 153
Tierna D. Jack Lawless Avatar answered Oct 23 '22 06:10

Tierna D. Jack Lawless


There is no className in react-native but you can use a style object in react-native like this:

<Text style={textStyle}>Some Words</Text>

const textStyle = {
    fontSize: 20
}

Note: Some style properties are in different name. for example the css font-size is fontSize in react-native

like image 45
Vahid Boreiri Avatar answered Oct 23 '22 06:10

Vahid Boreiri