0
0
React Nativemobile~5 mins

View component in React Native

Choose your learning style9 modes available
Introduction

The View component is like a box that holds other things on the screen. It helps organize and arrange parts of your app visually.

To group buttons and text together in one area.
To create sections or containers in your app layout.
To add background colors or borders around parts of the screen.
To control spacing and alignment of items inside the app.
To build complex layouts by nesting multiple Views.
Syntax
React Native
import { View } from 'react-native';

export default function Example() {
  return (
    <View style={{ width: 100, height: 100, backgroundColor: 'blue' }}>
      {/* Child components go here */}
    </View>
  );
}
The component can contain other components like Text, Image, or even other Views.
Use the style prop to control size, color, layout, and spacing.
Examples
This View adds padding and a background color around the text.
React Native
import React from 'react';
import { View, Text } from 'react-native';

export default function Example() {
  return (
    <View style={{ padding: 10, backgroundColor: 'lightgray' }}>
      <Text>Hello inside a View!</Text>
    </View>
  );
}
This View arranges two texts side by side with space between them.
React Native
import React from 'react';
import { View, Text } from 'react-native';

export default function Example() {
  return (
    <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
      <Text>Left</Text>
      <Text>Right</Text>
    </View>
  );
}
Sample App

This app shows two colored boxes stacked vertically in the center. Each box uses a View to create a colored area with centered text inside.

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

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.box}>
        <Text style={styles.text}>Box 1</Text>
      </View>
      <View style={[styles.box, styles.box2]}>
        <Text style={styles.text}>Box 2</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0'
  },
  box: {
    width: 150,
    height: 150,
    backgroundColor: 'skyblue',
    justifyContent: 'center',
    alignItems: 'center',
    margin: 10
  },
  box2: {
    backgroundColor: 'steelblue'
  },
  text: {
    color: 'white',
    fontSize: 18
  }
});
OutputSuccess
Important Notes

View is the most basic building block for layout in React Native.

Use flexbox styles on View to control layout direction and alignment.

Always give Views a size or flex value to make them visible.

Summary

The View component is a container for layout and styling.

It can hold other components and arrange them visually.

Use style props to control size, color, and layout inside Views.