This topic is about 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.
Next Topic : Click Here
Pingback: React Native - Props - Adglob Infosystem Pvt Ltd