Change background color of a View in React Native Tutorial from Scratch

In this tutorial, I am going to explain and show how we can change the background color of a View  in react native with complete source code. View  in react native is a very basic and useful component, which allows you to group multiple components in a single group with own custom styles, properties and methods. View  component of react native is very similar to the div  element of html .

Now, let’s get started.

Step #1: Create a new and fresh react native project, if you don’t know how to create a project in react native just follow this tutorial.

Step #2: Open your project in any editor( Visual Studio Code, Sublime etc. ) and open index.android.js  / index.ios.js  file. Remove all the code from this file and follow me, because we are going to start from scratch. 🙂

Step #3: Import all required components from react , react-native .

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

Step #4: Create a class and implement it’s render  and return  methods.

class App extends Component
{
    render()
    {
        return(
            <View style = { styles.container }></View>
        );
     }
}

Explanation:

  • In the above code block, we simply create a class  and returns a View  component with custom styles using styles.container .

Step #5: Implement styles for components.

const styles = StyleSheet.create(
{
     container:
     {
         flex: 1,
         backgroundColor: '#9FA8DA' // Set your own custom Color
     }
});

Explanation:

  • flex  is used to define the layout of the component and makes responsive layout, here 1 means that a component with ID container  takes whole remaining space on the screen. In our case, I have only one View component. So, it covers whole screen.

Step #6: Register your app with AppRegistry .

AppRegistry.registerComponent('App', () => App);

Complete Source Code for index.android.js / index.ios.js:

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

class App extends Component
{
    render()
    {
        return(
            <View style = { styles.container }></View> 
        );
     }
}

const styles = StyleSheet.create(
{
    container:
    {
        flex: 1,
        backgroundColor: '#9FA8DA' // Set your own custom Color
    }
});

AppRegistry.registerComponent('App', () => App);

Step #7: Run your app with react-native run-android  for android and react-native run-ios  for iOS devices.

  • Output in iOS emulator:

  • Output in Android emulator:

Please feel free to comment if you didn’t get any point… ? and Enjoy…

Leave a Reply

Your email address will not be published. Required fields are marked *