React.js / React Native Basics

Handling User Input and Navigation

This tutorial will teach you how to handle user interactions and navigation in your React Native app. You will learn how to capture user input, respond to user interactions and na…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Introduces React Native for building cross-platform mobile applications.

Introduction

In this tutorial, we aim to get you familiar with handling user input and navigation in a React Native app. By the end of this guide, you will be able to capture and respond to user interactions and navigate between different screens in your app.

You will learn:
- How to capture user input using built-in React Native components.
- How to handle user interactions such as button clicks.
- How to navigate between different screens in your app using React Navigation.

Prerequisites:
- Basic understanding of JavaScript and React.
- A working environment with React Native installed.

Step-by-Step Guide

Handling User Input

React Native provides built-in components such as TextInput and Button to handle user inputs.

TextInput

The TextInput component is used to capture text input from the user.

<TextInput 
  style={{height: 40, borderColor: 'gray', borderWidth: 1}}
  onChangeText={text => onChangeText(text)}
  value={value}
/>

Here, onChangeText is a function that gets called every time the text changes, and value is the current text present in the text box.

Button

The Button component is used to create a clickable button.

<Button
  onPress={onPressLearnMore}
  title="Learn More"
  color="#841584"
/>

The onPress function is called when the button is clicked.

Navigation

React Navigation is a popular library for handling navigation in a React Native app. Install it using the npm package manager:

npm install @react-navigation/native

Code Examples

Handling User Input

Let's create a simple login form to demonstrate user input.

import React, { useState } from 'react';
import { View, TextInput, Button } from 'react-native';

const LoginForm = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = () => {
    // Handle login functionality here
  };

  return (
    <View>
      <TextInput
        value={username}
        onChangeText={(text) => setUsername(text)}
        placeholder={'Username'}
      />
      <TextInput
        value={password}
        onChangeText={(text) => setPassword(text)}
        placeholder={'Password'}
        secureTextEntry={true}
      />
      <Button title={'Login'} onPress={handleLogin} />
    </View>
  );
};

export default LoginForm;

In this code, we're using React's useState hook to manage our form's state. When the user types into the TextInput fields, the corresponding state variables are updated. When the user presses the 'Login' button, the handleLogin function is called.

Navigation

Let's create two screens and navigate between them. First, install the stack navigator:

npm install @react-navigation/stack

Next, create two screens:

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

const HomeScreen = ({ navigation }) => (
  <View>
    <Text>Home Screen</Text>
    <Button title="Go to Details" onPress={() => navigation.navigate('Details')} />
  </View>
);

const DetailsScreen = () => (
  <View>
    <Text>Details Screen</Text>
  </View>
);

export { HomeScreen, DetailsScreen };

Then, create a stack navigator and include both screens:

import { createStackNavigator } from '@react-navigation/stack';
import { HomeScreen, DetailsScreen } from './screens';

const Stack = createStackNavigator();

const App = () => (
  <NavigationContainer>
    <Stack.Navigator initialRouteName="Home">
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="Details" component={DetailsScreen} />
    </Stack.Navigator>
  </NavigationContainer>
);

export default App;

In this code, pressing the button in the HomeScreen will navigate to the DetailsScreen.

Summary

You've learned how to handle user input and navigate between screens in a React Native app. You can now create more complex apps with multiple screens and user interactions.

Next, you could learn more about form validation and how to handle more complex navigation scenarios.

Additional resources:
- React Native Documentation
- React Navigation Documentation

Practice Exercises

  1. Create a signup form with fields for username, email, and password. Capture the input and print it to the console when a signup button is clicked.
  2. Create an app with three screens: Home, About, and Contact. Add navigation between these screens.
  3. Extend the app from exercise 2 by passing data between screens.

Remember to test your solutions and understand what each line of code is doing. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help