1.

What are the Different Ways to style React Native Application ?

Answer»

React Native GIVE us two powerful ways by default to style our application :

1 ) Style props

You can add styling to your component using style props. You simply add style props to your ELEMENT and it accepts an object of properties.

import React, {Component} from 'react';import {Platform, StyleSheet, Text, View} from 'react-native';export default class APP extends Component<Props> {render() {return (<View style={{flex:1,justifyContent:"center",backgroundColor:"#fff", alignItems:"center"}}><View style={{width:200,height:150,backgroundColor:"red",padding:10}}><Text style={{fontSize:20, color:"#666"}}>Styled with style props</Text></View></View>);}}

 2 )  Using StyleSheet

For an EXTREMELY  large codebase or you want to set many properties to your elements, writing our styling rules directly inside style props will make our code more complex that’s why React Native give us another way that let us write a concise code using the StyleSheet method:

import { StyleSheet} from 'react-native';const styles = StyleSheet.create({container: {flex:1,justifyContent:"center",backgroundColor:"#fff",alignItems:"stretch"},title: {fontSize:20,color:"#fff"},item1: {backgroundColor:"orange",flex:1},item2: {backgroundColor:"purple",flex:1},item3: {backgroundColor:"yellow",flex:1},});

 We then  pass the styles object to our component via the style props:

<View style={styles.container}><View style={styles.item1}><Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text></View><View style={styles.item2}><Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text></View><View style={styles.item3}><Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text></View><View style={styles.item4}><Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text></View></View>

3 ) styled-components in React Native

We can also use styled-components with React native so you can write your styles in React Native as you write normal CSS. It is very easy to include it in your project and it doesn’t need any linking just run this FOLLOWING command inside the root directory of your app to install it:

yarn add styled-components

import React, {Component} from 'react';import { StyleSheet,Text, View} from 'react-native';import styled from 'styled-components'const Container=styled.View` flex:1; padding:50px 0; justify-content:center; background-color:#f4f4f4; align-items:center`const Title=styled.Text`font-size:20px;text-align:center;color:red;`const Item=styled.View`flex:1;border:1px solid #ccc;margin:2px 0;border-radius:10px;box-shadow:0 0 10px #ccc;background-color:#fff;width:80%;padding:10px;`export default class App extends Component { render() { return ( <Container> <Item > <Title >Item number 1</Title> </Item> <Item > <Title >Item number 2</Title> </Item> <Item > <Title >Item number 3</Title> </Item> <Item > <Title >Item number 4</Title> </Item> </Container> ); }


Discussion

No Comment Found