React Native - Styling




React Native - Styling

There are a couple of ways to style your elements in React Native.

You can use the style property to add the styles inline. However, this is not the best practice because it can be hard to read the code.

In this chapter, we will use the Stylesheet for styling.

Container Component

In this section, we will simplify our container component from our previous chapter.

App.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import PresentationalComponent from './PresentationalComponent'

export default class App extends React.Component {
   state = {
      myState: 'This is my state'
   }
   render() {
      return (
         <View>
            <PresentationalComponent myState = {this.state.myState}/>
         </View>
      );
   }
}

Presentational Component

In the following example, we will import the StyleSheet. At the bottom of the file, we will create our stylesheet and assign it to the styles constant. Note that our styles are in camelCase and we do not use px or % for styling.

To apply styles to our text, we need to add style = {styles.myText} property to the Text element.

PresentationalComponent.js

import React, { Component } from 'react'
import { Text, View, StyleSheet } from 'react-native'

const PresentationalComponent = (props) => {
   return (
      <View>
         <Text style = {styles.myState}>
            {props.myState}
         </Text>
      </View>
   )
}
export default PresentationalComponent

const styles = StyleSheet.create ({
   myState: {
      marginTop: 20,
      textAlign: 'center',
      color: 'blue',
      fontWeight: 'bold',
      fontSize: 20
   }
})

When we run the app, we will receive the following output.

React Native - Styling



Frequently Asked Questions

+
Ans: React Native - Props view more..
+
Ans: React Native - State view more..
+
Ans: React Native - App view more..
+
Ans: React Native - Styling view more..
+
Ans: React Native - Flexbox view more..
+
Ans: React Native - ListView view more..
+
Ans: React Native - Text Input view more..
+
Ans: React Native - ScrollView view more..
+
Ans: React Native - Images view more..
+
Ans: React Native - HTTP view more..
+
Ans: React Native - Buttons view more..
+
Ans: React Native - Animations view more..
+
Ans: React Native - Debugging view more..
+
Ans: React Native - Router view more..
+
Ans: React Native - Running IOS view more..
+
Ans: React Native - Running Android view more..
+
Ans: React Native - View view more..
+
Ans: React Native - WebView view more..




Rating - NAN/5
529 views

Advertisements