What is a View component and how to use it in React Native?


View is the most common as well as the core element in React Native. You can consider it as an equivalent of the div element used in web development.

View will map to its native equivalent based on the platform it is running. So on android the view will map to <ViewGroup>, on iOS it will be <UIView> and <div> on the web environment.

Use Cases

Let us now see a few common use cases.

  • When you need to wrap your elements inside the container, you can use View as a container element.

  • When you want to nest more elements inside the parent element, both parent and child can be View. It can have as many children as you want.

  • When you want to style different elements, you can place them inside View since it supports style property, flexbox etc.

  • View also supports synthetic touch events, which can be useful for different purposes.

Example 1: Displaying Text Inside View

This example creates a View component that wraps two View Components. Both the View component has a Text component inside it.

The component you want to work with has to be imported first. In the example, I am working with View and Text so both are imported from react-native as shown below −

import { Text, View} from 'react-native';
import React, { Component } from "react";
import { Text, View} from 'react-native';
class App extends Component {
   render(props) {
      return (
         <View style={{flex :1, justifyContent: 'center', margin: 15 }}>
            <View>
               <Text style={{color:'green', fontSize:30}}> View Component </Text>
            </View>
               <View>
                  <Text style={{color:'red', fontSize:25}}>Welcome to Tutorialspoint</Text>
            </View>
         </View>
      );
   }
}
export default App;

Output

Example 2: Displaying Text/TextInput/Button Inside View

This example creates a View component that has three view Components each with Text, TextInput and a Button.

To work with components in react-native import them first as shown below −

import { Text, View, TextInput, Button} from 'react-native';
import React, { Component } from "react";
import { Text, View, TextInput, Button} from 'react-native';
class App extends Component {
   render(props) {
      return (
         <View style={{flex :1, justifyContent: 'center', margin: 15 }}>
            <View>
               <Text style={{color:'green', fontSize:30}}> View Component </Text>
            </View>
         <View>
            <TextInput style={{ height: 40, borderColor: 'black', borderWidth: 1 }}             defaultValue="Type something here" />
         </View>
            <View>
               <Button title="Click Me" color="red" />
            </View>
         </View>
      );
   }
}
export default App;

Output

Updated on: 01-Jul-2021

658 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements