StyleSheet Component in React-Native

StyleSheet Component in React-Native

ยท

3 min read

Table of contents

The StyleSheet component in React Native defines styles for components in a mobile app. It acts as a container for a set of style rules, which can be applied to one or more components.

The StyleSheet is way similar to that of CSS Stylesheet. StyleSheet provides a way to encapsulate styles in a single place and reuse them throughout the app, making it easier to maintain and update the look and feel of the app.

For example, if we wanted to give the same font face to both our main heading and the sub-headings we can just define one container that contains the font face and can then apply it to all the main headings and the sub-headings. By doing this, we don't have to repeat to style each of them separately.

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

function AppPro() : JSX.Element {
    return(
        <View style = {styles.container}>
            <Text style = {styles.text}>
                It's fun to learn React Native.
            </Text>
        </View>
    )
}

const styles = StyleSheet.create({
    container : {
        flex : 1,
        justifyContent : 'center',
        alignItems : 'center',
    },

    text : {
        color : 'purple',
        fontSize: 20,
    },
});

export default AppPro;

In this example, a StyleSheet component is used to define two styles: "container" and "text". The "container" style is applied to the View component and sets its layout properties which make the text appear in the center. The "text" style is applied to the Text component and sets its font size and colour.

These styles are defined in a single place, making it easier to manage and maintain the look and feel of the app. The output of the above code is given below -


There are some of the methods of this component -

Methods

compose() -

This method in React Native's StyleSheet component allows developers to combine multiple styles into a single style object. This method takes two or more styles as arguments and returns a new style object that combines the styles passed in.

It combines two styles such that style2 will override any styles in style1.

create() -

This method defines a set of styles for components. It takes an object as an argument, where the keys are the style rule names and the values are objects that define the style rules.

Each style object can contain one or more style rules, such as color, font size, margin, padding, and more. The values for these rules can be any valid CSS-like value, such as a number, a string, or an object.

flatten() -

This method is used to combine an array of style objects into a single, flattened style object. This method takes an array of styles as an argument and returns a new style object that contains all of the styles merged together.


That's all for this one. Hope you learned something from this.

Happy Learning! ๐Ÿ˜€

ย