# How to handle errors while working with Navigation in ReactNative?

React NativeJavascriptMobile Development

Problem: How to handle the error “A navigator can only contain 'Screen' components as its direct children” while working with Navigation in ReactNative?

## Solution

While working on your app you may come across issues like stated above. Here will understand why such error comes up and what can be done to avoid it.

Here is the code that gives us the error −

## Example

App.js

import * as React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import { Button, View, Alert, Text } from 'react-native';
const Stack = createStackNavigator();
const HomePage = ({ navigation }) => {
return (
);
};
const AboutPage = () => {
return <Text>You have reached inside About Page!</Text>;
};
const MyStack = () => {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomePage}
/>
</Stack.Navigator>
);
};
export default MyStack;

The error displayed is as follows in your command prompt while compiling −

The display of error on your phone screen is as follows −

Reasons for the Error − A navigator can only contain 'Screen' components as its direct children

The first cause for the error is because of bad indentation. It is very necessary that each component is indented properly. The child elements are indented properly inside the parent component.

The second case is because of spaces left at the end of each component. Remove the spaces from the end of the screen and compile again. It will work fine. Please be careful when copy pasting the code from another source. You will encounter this error mostly in those cases.

Let us now indent the above code and also remove spaces if any. Here is the final code with output.

## Example

import * as React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import { Button, View, Alert, Text } from 'react-native';
const Stack = createStackNavigator();
const HomePage = ({ navigation }) => {
return (
);
};
const AboutPage = () => {
return <Text>You have reached inside About Page!</Text>;
};
const MyStack = () => {
return (
export default MyStack;