-
There is no css in react-native, we use javascript to style our code.
-
You have two ways to style an element:
-
Inside the tag itself like
<View style={{ width: 100, height: 100, backgroundColor: "blue" }} />
-
Use StyleSheet
// don't forget to import StyleSheet import { StyleSheet } from "react-native"; export default App = () => ( // call your style sheet <View style={styles.container}> <Text>hello from react Native</Text> </View> ); // create StyleSheet const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "white", alignItems: "center", justifyContent: "center", paddingTop: Platform.OS === "android" ? StatusBar.CurrentHeight : 0, }, });
You can pass more than one style by nesting all styles in an array like:
<View style={[styles.container ,styles.formContainer]}>
It's recommended to use StyleSheet for many reasons:
-
By moving styles away from the render function, you're making the code easier to understand.
-
Naming the styles is a good way to add meaning to the low level components in the render function.
-
Making a stylesheet from a style object makes it possible to refer to it by ID instead of creating a new style object every time.
-
It also allows to send the style only once through the bridge. All subsequent uses are going to refer an id (not implemented yet).
-
StyleSheet check your syntax and throw an error when you have something wrong in you style.
-
Look at this example:
<View style={{ width: 150, height: 150 }} />
What is the dimensions used in react-native?
-
In react-native we use "DIP" = Density-Independent-pixel , so in our example width and height are 100 dips, and the actual size on the mobile will be 100 x Scale Factor.
-
Use Dimension or useWindowDimension to know the exact dimension of your mobile screen.
Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.
We use flex property to specify how the item grow to fill the available space.
<View style={{styles.container}}>
<View style={backGroundColor:'tomato', flex:1}>
<View style={backGroundColor:'gold', flex:2}>
<View style={backGroundColor:'greenyellow ', flex:3}>
<View>
it's like regular css, but the default position is 'relative'