0
0
React-nativeHow-ToBeginner ยท 3 min read

How to Use View in React Native: Simple Guide

In React Native, View is a container component used to layout and style UI elements. You use it by importing from react-native and wrapping other components or content inside it. It works like a div in web development but supports mobile-specific styling and layout.
๐Ÿ“

Syntax

The View component is imported from react-native and used as a wrapper for other components or UI elements. It accepts style props to control layout, size, and appearance.

  • import: Bring View from react-native.
  • View tag: Wraps children components.
  • style prop: Customize layout and look.
javascript
import { View } from 'react-native';

export default function App() {
  return (
    <View style={{ flex: 1, backgroundColor: 'blue' }}>
      {/* Child components go here */}
    </View>
  );
}
Output
A blue full-screen container that can hold other components.
๐Ÿ’ป

Example

This example shows a simple screen with a red box centered inside a full-screen View. It demonstrates how to use View for layout and styling.

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

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.box} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#eee'
  },
  box: {
    width: 100,
    height: 100,
    backgroundColor: 'red'
  }
});
Output
A gray screen with a centered red square box of 100x100 pixels.
โš ๏ธ

Common Pitfalls

Common mistakes when using View include:

  • Not setting flex or size, causing the View to collapse and not appear.
  • Forgetting to import View from react-native.
  • Using unsupported style properties or invalid values.
  • Not wrapping multiple children inside a single View or fragment.
javascript
/* Wrong: View with no size collapses */
<View style={{ backgroundColor: 'blue' }} />

/* Right: Add flex or fixed size */
<View style={{ flex: 1, backgroundColor: 'blue' }} />
Output
Wrong: No visible box. Right: Blue full-screen box visible.
๐Ÿ“Š

Quick Reference

View Component Cheat Sheet:

  • flex: Controls how View grows or shrinks.
  • justifyContent: Aligns children vertically.
  • alignItems: Aligns children horizontally.
  • backgroundColor: Sets background color.
  • padding and margin: Space inside and outside the View.
โœ…

Key Takeaways

Use View as a container to layout and style UI elements in React Native.
Always import View from react-native before using it.
Set size or flex properties to make View visible and control layout.
Use style props like justifyContent and alignItems to position children.
Avoid common mistakes like missing size or invalid styles to ensure your View renders correctly.