Open In App

How to style React Native Application ?

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • The first view component is formatted as a flexbox with a value of 1 to fill over the available space along your main axis. 
  • The code looks similar to CSS but it’s not CSS you can see the properties are written in camel case notation justifyContent instead of justify-content in CSS. 
  • Some properties are not supported in react-native such as CSS animations. 

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.

  • In the following code above, we converted the inline styles into a StyleSheet object, this object contains all the styles that we used in the previous example.
  • We can reuse this style object with different elements. we can create another box and assign the same properties as we assigned to the blue box in this example. 

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

App.js

 

Output: 

OUTPUT 3


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads