Open In App

How to style React Native Application ?

In this article, we’ll learn how to style React Native applications. There are two major ways to style your React Native Application:

  1. Style Props
  2. Using StyleSheet

Method 1: Style Props: To style an element with the style props, the value must be a JavaScript Object. You just have to add a style prop to your element. 



Syntax:

<View style={{}}> </View>

Creating Application: Follow the below steps to create an application:



Step 1: Open your terminal and install expo-cli by the following command.

npm install -g expo-cli

Step 2: Now create a project by the following command.

expo init Project

Step 3: Now go into your project folder i.e. StyleExample

cd Project

Project Structure: The project structure should look like this:

Project Structure

Example 1: This example will demonstrate the style of props. Write the below code in the App.js file.

App.js
 

Steps to run the application: Start the server by using the following command.

npm run android

Output:

OUTPUT 1

Method 2: Using StyleSheet: StyleSheets separates the style code from the main elements, It makes the code easier to understand and increases the code usability. In large code bases adding inline styles for each element can become messed up that’s why stylesheets are used.

To use the stylesheet in your code, first import the stylesheet:

import { StyleSheet} from 'react-native';

Syntax:

const styles = StyleSheet.create({ 
    style1Name: { }, 
    style2Name: { }, 
    style3Name: { }
});

Example 2: Let’s convert the Example 1 code into styleSheet to demonstrate the use of Stylesheet. Write the below code in the App.js file.

App.js
 

Output:

OUTPUT 2

As shown in the code we created a StyleSheet object and defined styles for each element separately. These styles are accessed using (.) for example myStyles.txtStyle.

Example 3: This example will demonstrate StyleSheet. Write the below code in the App.js file.

App.js
 

Output: 

OUTPUT 3

Article Tags :