React-Navigation in React-Native

React-Navigation in React-Native

Day-6

Documentation

React-navigation

Custom Transitions in React Navigation | by Daniel Merrill | Async | Medium

App.tsx

import {View, Text, SafeAreaView, ScrollView, StatusBar} from 'react-native';
import React from 'react';

import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import HomeScreen from './Screens/HomeScreen';
import ProfileScreen from './Screens/ProfileScreen';
import UserScreen from './Screens/UserScreen';

const App = () => {
  const Stack = createNativeStackNavigator();
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{
            headerStyle: {backgroundColor: '#68D2E8'},
            statusBarColor: '#03AED2',
            headerTintColor: 'white',
            headerTitleStyle: {
              fontWeight: 'bold',
              fontSize: 20,
            },
            headerTitleAlign: 'center',
          }}
        />
        <Stack.Screen
          name="Profile"
          component={ProfileScreen}
          options={{
            title: 'Profile details',
            headerStyle: {backgroundColor: '#03AED2'},
            statusBarColor: '#03AED2',
            headerTintColor: 'white',
            headerTitleStyle: {
              fontWeight: 'bold',
              fontSize: 20,
            },
          }}
        />
        <Stack.Screen
          name="User"
          component={UserScreen}
          options={{title: 'User details', statusBarColor: '#03AED2'}}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

This React Native code sets up a simple navigation system for a mobile application using the React Navigation library. Here’s a straightforward explanation of what each part does:

Setup and Imports

  • React and React Native Elements: The code begins by importing necessary components from react-native, including View, Text, SafeAreaView, ScrollView, and StatusBar, which are common components for layout and display.

  • React Navigation Components: NavigationContainer and createNativeStackNavigator are imported from @react-navigation/native and @react-navigation/native-stack respectively. These are essential for handling navigation between different screens in the app.

Navigation Setup

  • Stack Navigator: The createNativeStackNavigator is a function that returns a navigator component with stack-based navigation, allowing users to open pages and go back to the previous ones.

  • Navigation Container: The NavigationContainer wraps around the entire navigation structure. It manages the navigation tree and contains the navigation state. This component must wrap all navigators structure.

Screens and Navigation

  • Inside the NavigationContainer, a Stack.Navigator is defined, which holds individual Stack.Screen components. Each screen component represents a page in your app.

  • InitialRouteName: The navigator is configured with initialRouteName="Home", setting the HomeScreen as the first screen displayed when the app loads.

Stack Screens

  • Home Screen: Configured as the first screen. It uses the HomeScreen component. Navigation options like header style, title style, and status bar color are customized.

    • headerStyle: Background color of the navigation bar is set to a teal color.

    • headerTintColor: Color of the back button and title in the header.

    • headerTitleStyle: Style for the header title including font weight and size.

    • headerTitleAlign: The title is centered.

  • Profile Screen: Uses the ProfileScreen component. Similar options are set for appearance as in the Home screen, but the title is explicitly set to "Profile details".

  • User Screen: Uses the UserScreen component. It has simpler options, only setting the title to "User details" and the status bar color.

Function and Export

  • The App component is a functional component that defines the navigation structure. It’s exported as the default export of the module, meaning this setup is the main entry point of the app.

Summary

This code effectively sets up a three-page application with a navigation bar at the top. Users can navigate between the Home, Profile, and User screens. Styling options ensure the app has a cohesive color scheme and typography in the header across different screens. This setup is typical for apps needing basic navigation between multiple screens while maintaining a uniform style.

HomeScreen.jsx

import { Button, Image, ImageBackground, StyleSheet, Text, View, TextInput } from 'react-native';
import React, { useState } from 'react';

export default function HomeScreen(props) {
  console.log(props);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [enrolno, setEnrolno] = useState("");
  return (
    <View style={styles.container}>
      <ImageBackground
        source={{ uri: 'https://images.unsplash.com/photo-1595912587923-bdffd4564f33?q=80&w=1031&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D' }} style={[styles.cardImage, styles.ImageBackground]}
      >
        <Text style={styles.headingText}>React-Navigation</Text>
        <TextInput style={styles.textInput} placeholder='Enter Name' onChangeText={(text) => setName(text)} />
        <TextInput style={styles.textInput} placeholder='Enter Email' onChangeText={(email) => setEmail(email)} />
        <TextInput style={styles.textInput} placeholder='Enter Enroll No.' onChangeText={(number) => setEnrolno(number)} />
        <Button
          title="Send Details"
          onPress={() =>
            props.navigation.navigate('User', {
              name, email, enrolno
            })
          }
        />
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  headingText: {
    fontSize: 30,
    fontWeight: 'bold',
    color: 'white',
    textAlign: 'center',
    padding: 10,
  },
  cardImage: {
    width: '100%',
    height: '100%',
  },
  ImageBackground: {
    justifyContent: 'center',
    alignItems: 'center',

  },
  textInput: {
    color: 'black',
    width: '80%',
    height: 40,
    borderColor: 'black',
    borderWidth: 1,
    borderRadius: 10,
    padding: 10,
    margin: 10,
    backgroundColor: 'white',
  }
});

The React Native code you've provided is for a HomeScreen component that features a form with inputs for user details set against a background image. Here’s a concise breakdown:

Functionality:

  • State Management: Uses useState to handle user inputs for name, email, and enrollment number.

  • User Input: Provides three TextInput fields for users to enter their details.

  • Navigation: Includes a Button that, when pressed, navigates to a 'User' screen and passes the input data as parameters.

Layout:

  • Background: Utilizes an ImageBackground to enhance visual appeal.

  • Styling: The component is styled with centralized content and styled text inputs for clear visibility and interaction.

Interaction:

  • Submit Action: The "Send Details" button submits the data and triggers navigation to another screen with the entered data.

This setup is typical for forms in mobile apps, combining aesthetic elements with functionality for data entry and screen navigation in React Native.

UserScreen.jsx

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

export default function UserScreen(props, route) {
  console.log(props);

  const { name, email, enrolno } = props.route.params;

  return (
    <View style={styles.container}>
      <ImageBackground
        source={{ uri: 'https://images.unsplash.com/photo-1511367461989-f85a21fda167?q=80&w=1031&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D' }}
        style={styles.cardImage}>
        <Text style={styles.headingText}>Name: {name}</Text>
        <Text style={styles.headingText}>Email: {email}</Text>
        <Text style={styles.headingText}>Enroll No: {enrolno}</Text>
        <Button
          title="Profile Details"
          onPress={() =>
            props.navigation.navigate('Profile', {
              name
            })
          }
        />
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  headingText: {
    fontSize: 20,
    fontWeight: 'bold',
    color: 'white',
    padding: 10,
  },
  cardImage: {
    width: '100%',
    height: '100%',
  },
  ImageBackground: {
    justifyContent: 'center',
    alignItems: 'center',

  }
});

The React Native code defines a functional component named UserScreen which displays user information overlaid on a background image. Here's a concise overview of the component's functionality and structure:

Functionality:

  • User Information Display: The component extracts user data (name, email, and enrolno) from the navigation parameters passed from the previous screen using props.route.params.

  • Navigation Button: Includes a button that navigates to a 'Profile' screen, passing the user's name as a parameter.

Layout:

  • ImageBackground: Uses an ImageBackground component to set a visually appealing background image fetched from a URL.

  • Text Display: Displays the user's name, email, and enrollment number as text over the background image.

Styling:

  • Container: Centers its contents both horizontally and vertically.

  • Text Styling: Applies styling to text elements to enhance readability against the background, including setting the font size, weight, color, and padding.

  • Background Image Styling: Ensures the background image fills the entire space of the component.

Code Summary:

  • The UserScreen component is designed to present detailed information fetched from previous interactions, effectively utilizing an ImageBackground for aesthetic appeal while maintaining functional simplicity through clear text displays and straightforward navigation functionality. This setup is common in applications where passing and displaying user-specific data is required, ensuring a seamless user experience.

ProfileScreen.jsx

import { ScrollView, StyleSheet, Text, View } from 'react-native';
import React from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import FancyCard from '../components/FancyCard';
import Actioncard from '../components/Actioncard';

export default function ProfileScreen(props, route) {
  const { name } = props.route.params;
  return (
    <SafeAreaView>
      <ScrollView>
        <View style={styles.container}>
          <Text style={styles.headingText}>Profile Details</Text>
          <View style={styles.container}>
            <Text style={styles.headerText}>Name: {name}</Text>
          </View>
        </View>
        <Actioncard />
        <FancyCard />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  headingText: {
    fontSize: 20,
    fontWeight: 'bold',
    color: 'black',
    padding: 10,

  },
  headerText: {
    fontSize: 20,
    fontWeight: 'bold',
    color: 'black',
  },

});

The React Native code you provided defines a functional component named ProfileScreen. This component is designed to display profile details, specifically the user's name, along with additional content cards. Here’s a breakdown of its structure and functionality:

Components Used:

  • SafeAreaView: Ensures that the UI elements are rendered within the safe area boundaries of the device. It is useful for avoiding notches and intrusive system UI on modern mobile devices.

  • ScrollView: Allows for scrolling when the content exceeds the screen space. This component wraps all other content, making the screen scrollable vertically.

  • FancyCard and Actioncard: Custom components imported and used within the screen. These likely display specific information or actions related to the user or application.

Functionality:

  • Name Display: The component retrieves the user's name from the navigation parameters passed via props.route.params and displays it prominently at the top of the screen.

  • Integration of Custom Cards: Incorporates two custom card components, FancyCard and Actioncard, which might show additional user-related data or provide interaction options.

Layout and Styling:

  • General Layout: Uses a ScrollView for the main content area, ensuring that the content can be scrolled through if it exceeds the screen's viewable area.

  • Styling:

    • container: Applied to the View containing the text elements, this style sets the component to use full available space (flex: 1), centers its children horizontally (alignItems: 'center'), and sets a light background color (backgroundColor: '#F5FCFF').

    • headingText and headerText: Both text styles are similar, marking the text as bold, black, and sized at 20 pixels. headingText also includes padding.

Code Summary:

This ProfileScreen component is a straightforward example of a profile page in a mobile app, showing basic user information and incorporating custom components for additional functionality or data display. The use of SafeAreaView and ScrollView ensures that the app’s UI is both safe for device-specific display issues and user-friendly for browsing extensive content. The component structure promotes clean separation of the profile header from interactive or informative card components, making the screen both functional and modular.

React Native react js JavaScript