From Zero to Hero: Build Your First React Native App in 1 Hour

prankurpandeyy

PRANKUR PANDEY

Posted on September 2, 2024

From Zero to Hero: Build Your First React Native App in 1 Hour

1. Introduction

  • Overview of React Native

What is React Native?
React Native is a JavaScript framework for building mobile apps for Android and iOS It is:

  • Cross-platform: React Native allows developers to create platform-specific versions of components and use the same codebase for both iOS and Android.
  • Native components: React Native uses native components instead of web components.
  • Efficient and versatile: React Native is designed to create apps that are responsive and intuitive.
  • Based on React: React Native is based on React, Facebook's JavaScript library for building user interfaces.
  • Supports new JavaScript features:React Native supports new JavaScript (ES6+) features, such as arrow functions and async/await.

Why use React Native for mobile development?
If you are coming from React and JavaScript Background it is pretty easy to pick up React Native , you do not have to learn Java or Kotlin to build Android Apps and Swift for the iOS apps.

  • Vast library support makes React Native easy to integrate with third party libraries to get the job done.
  • Huge community support so if you are stuck at something you can ask to the community.

Prerequisites

  • Basic knowledge of JavaScript and React.
  • Development environment setup (Windows, macOS, Linux).

2. Setting Up the Development Environment

  • Installing Node.js
    • Based on the OS the NodeJS provide different binaries you go to the nodejs official website and download the binaries once downloaded you can install it easily.
    • Installing JDK- Install JDK from official JAVA website or you can also choose any JDK of your choice, the version should be above 17
  • Installing React Native CLI
    • Introduction to React Native CLI vs Expo CLI. React Native apps can be build with two methods one is standard React Native CLI and another is Expo CLI ,expo provides many things preconfigured for the development which you will have to do separately in React Native CLI ,so making apps with expo is bit easy also if you are building with expo you don't need to attach a physical mobile device with development machine expo will give the QR just scan the QR Code with expo go app installed on the phone and you are good to go.
    • Here are the commands for Installing expo CLI :npm install --global expo-cli. global is used to install the CLI globally on machine
    • Here are the commands for Installing React Native CLI : npx @react-native-community/cli@latest
  • Setting Up Android Studio (for Android Development)

    • Download Android Studio
    • Once Android Studio is installed run the Studio and when first time setup occurs check these boxes and click on apply/install
    • Android SDK
    • Android SDK Platform
    • Android Virtual Device
  • Setting Up Home Environemnt (for Android Development)

    • Set Java Home Path
    • Set Android Home Path
    • Set Android SDK Path
    • Set Android Emulator Path
    • Set Android Paltform Tools Path I am using Linux so after setting up everything in my bash file it looks something like this

Image description
Save the file and restart the system if everything goes well the environment setup is done.

3. Creating Your First React Native Project

  • Starting a New Project
    • Command to create a new React Native project. Run This command in terminal :npx @react-native-community/cli@latest init myAppRun this command and It will generate a new react native project with the name of myApp here is how it looks like after creating project

Image description

  • Explanation of the project structure.

    We have multiple folders but I will only focus on important ones, lets understand each folder:

    Android : This folder contains android related files such as gradle builds,minmap file responsible for android logo updation etc.

  • App.tsx : This file holds your whole project anything which holds project data such as pages,components,images can be hold here .

  • package.json : This is responsible for handling packages/libraries installed as third party in project.

  • index.js : the file serve as root for the project ,when projects run the builder looks for this file only.

  • test: the file holds test cases for the project

    • Running the Project on an Emulator/Device
  • I am building the application for the Android so you need an Android Phone and enable USB debugging then connect your phone to the machine and run this command in terminal where your React Native Project is located run this command : npm start
    Image description
    It will launch the app on your phone something like this:
    Image description

    • After launching the app you can see a dummy mobile phone appears it is emulator, therefore we have previously configured Android Home and Emulator tools path.

4.Understanding the Basics of React Native

  • Core Components
  • In React Native there are various components and each component has It own uses today I will be discussing about the few main components which I will using in building this project
    • Explanation and examples of View, Text, Image, TextInput, Button :
    • View : The View component is main components in React Native responsible for displaying anything you can consider this as div of html.
    • Text : The Text component is responsible for displaying text like we have paragraphs,heading in html and we have different tags to do this but in React Native to display simple text ,the Text component is used .
    • Image : The Image component is same as the Image component of HTML.
    • Text Input : The Text Input component is responsible for taking text as input consider this component as text input component of HTML. -** Button :** The Button component is same as the Button component of HTML.
  • Styling in React Native
    • How to style components using StyleSheet : In React Native there are two ways to style components first is inline styling and another is using Stylesheet.,stylesheet takes objects as styles for different style names for each component.
    • Using libraries for styling : There are multiple component libraries available in market and each has its own unique components and features libraries work like plug and play working model simply install the library and start importing components.
    • Flexbox layout for responsive design: To Achieve responsive design in React Native flexbox is availble ,this flexbox works same as the flexbox of vanilla CSS ,even most of the styles of CSS can be declared and used in React Native.
  • Handling User Input User input can be handles same as we handle in react using event handlers.

5. State Management in React Native

  • Using the useState Hook

    • In JavsScript if we have to hold the datawe use variables in variables we have three variable methods to do it ,let,var and const these are three data holding points but in React we have hooks like useState to hold the data and use it when needed , same goes for React Native the useState hook of React works in same way it works in ReactJS. Here is an example : ``` import React, { useState } from 'react'; import './App.css';

    function App() {
    // Step 3: Using useState Hook to handle state
    const [count, setCount] = useState(0); //storing data in count variable

    // Step 4: Increment and Decrement Functions
    const increment = () => {
    setCount(count + 1);
    };

    const decrement = () => {
    setCount(count - 1);
    };

    return (

    Simple Counter App

        {/* Step 5: Displaying the Count */}
        <p>Count: {count}</p>
    
        {/* Step 6: Buttons to Increment and Decrement */}
        <button onClick={increment}>Increment</button>
        <button onClick={decrement}>Decrement</button>
      </header>
    </div>
    

    );
    }

    export default App;

  • Data and Component Communication

    • Data handling is very crucial in every application and supply of data should be consistent in whole application to do this in React Native we can apply same data logic which we use in React like using of states for holding data and later supplying it into the whole app.
    • Supply of data in whole app is challenging as there are methods and libraries to do it using like redux,zod etc and there are native methods like ContextAPI and Reducers .If the app size is small we can also use prop dirilling to pass the data .
  • 6. Working with APIs

    • Fetching Data from an API

      • Introduction to fetch and axios. Data fetching is most part in applications as it abstract the backend without exposing business logic,As there are two methods which I personally prefer using for data fetching one is Axios and another is native browser methods Fetch Axios is a third party library built on top of fetch ,fetch is native method of browsers allows data fetching from api url but due to its some limitations and handling of complex HTTP request is bit tricky axios is more popularalso fetch doesn't transform json data while axios does. Also error handling is easy in axios compare to Fetch.

    7. Building the React Native App

    • What I am building I am building a simple React Native Android App where users will get the news every time they click on fetch news button.
    • Tech Stack
      • React Native
      • Axios
      • News API
    • Screens First I will be building the sample homepage for the app which looks something like this

    Image description

    Here is the full code of building screens :

    • ``` import React, {useState} from 'react'; import {View, Text, Button, StyleSheet, ActivityIndicator} from 'react-native'; import axios from 'axios';

    const Homepage = () => {
    const [news, setNews] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

const fetchNews = () => {
  // Set the loading indicator to true and clear out any error messages.
  setLoading(true);
  setError(null);

  // Make a GET request to the News API. We'll pass in some parameters to
  // customize the request. The country parameter is set to the US, but you can
  // change this to any other country code supported by the API.
  // The apiKey parameter is set to your API key that you got when you signed
  // up for the News API.
  // The pageSize parameter is set to 1, which means that we'll only get one
  // article back. If you want to get more articles, just increase this number.
  // Finally, the page parameter is set to a random number between 1 and 100.
  // This is just to make sure that we don't always get the same article.
  axios
    .get('https://newsapi.org/v2/top-headlines', {
      params: {
        country: 'us',
        apiKey: '8e7c1fc79b26406d87a58370170b37a9',
        pageSize: 1,
        page: Math.floor(Math.random() * 100) + 1,
      },
    })
    .then(response => {
      // If the request was successful, set the news to the first article in the
      // response. The response is an object with an articles array in it, which
      // contains the articles.
      setNews(response.data.articles[0]);
      // Set the loading indicator to false, since we're done fetching the data.
      setLoading(false);
    })
    .catch(error => {
      // If the request failed, set the error message to an error message.
      setError('Failed to fetch news');
      // Set the loading indicator to false, since we're done trying to fetch
      // the data.
      setLoading(false);
    });
};

return (
  <View style={styles.container}>
    {loading && <ActivityIndicator size="large" style={styles.loading} />}

    {!loading && !news && !error && (
      <Text style={styles.message}>Click on the button to fetch news</Text>
    )}

    {error && <Text style={styles.error}>{error}</Text>}
    <View style={styles.dataContainer}>
      {news && (
        <View style={styles.newsContainer}>
          <Text style={styles.description}>Author: {news.author}</Text>
          <Text style={styles.title}>News : {news.title}</Text>
        </View>
      )}
      <Button title="Fetch News" onPress={fetchNews} />
    </View>
  </View>
);

};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: 300,
width: 300,
},
loading: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
message: {
fontSize: 20,
},
error: {
fontSize: 20,
color: 'red',
},
newsContainer: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
backgroundColor: 'blue',
padding: 20,
borderRadius: 10,
borderWidth: 1,
borderColor: 'black',
marginTop: 10,
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
description: {
fontSize: 18,
color: 'black',
},
dataContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
width: 300,
height: 300,
marginTop: 10,
},
button: {
marginTop: 10,
},
});

export default Homepage;


Explanation of this code : 


This code is a React Native component called `Homepage` that fetches a news article from the News API and displays it when the user clicks a "Fetch News" button. Here's a detailed breakdown:

### **Imports**

```javascript
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet, ActivityIndicator } from 'react-native';
import axios from 'axios';
  • React: Core library for building user interfaces.
  • useState: A React hook that allows you to manage state in functional components.
  • View, Text, Button, StyleSheet, ActivityIndicator: Core components from React Native to build the UI.
  • axios: A promise-based HTTP client for making requests to a server.

State Management

const [news, setNews] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
  • news: Stores the fetched news article.
  • loading: A boolean that tracks whether the app is currently fetching data.
  • error: Stores an error message if the API request fails.

fetchNews Function

const fetchNews = () => {
  setLoading(true);
  setError(null);

  axios
    .get('https://newsapi.org/v2/top-headlines', {
      params: {
        country: 'us',
        apiKey: '8e7c1fc79b26406d87a58370170b37a9',
        pageSize: 1,
        page: Math.floor(Math.random() * 100) + 1,
      },
    })
    .then(response => {
      setNews(response.data.articles[0]);
      setLoading(false);
    })
    .catch(error => {
      setError('Failed to fetch news');
      setLoading(false);
    });
};
  • setLoading(true): Activates the loading state.
  • axios.get(): Makes a GET request to the News API.
    • params: Specifies the request parameters:
    • country: Fetches news from the US.
    • apiKey: Your API key for accessing the News API.
    • pageSize: Limits the response to one article.
    • page: Fetches a random page to ensure different articles are fetched each time.
  • setNews(response.data.articles[0]): Stores the first article from the response.
  • setLoading(false): Deactivates the loading state.
  • setError('Failed to fetch news'): Sets an error message if the request fails.

Rendering the UI

return (
  <View style={styles.container}>
    {loading && <ActivityIndicator size="large" style={styles.loading} />}

    {!loading && !news && !error && (
      <Text style={styles.message}>Click on the button to fetch news</Text>
    )}

    {error && <Text style={styles.error}>{error}</Text>}

    <View style={styles.dataContainer}>
      {news && (
        <View style={styles.newsContainer}>
          <Text style={styles.description}>Author: {news.author}</Text>
          <Text style={styles.title}>News : {news.title}</Text>
        </View>
      )}
      <Button title="Fetch News" onPress={fetchNews} />
    </View>
  </View>
);
  • ActivityIndicator: Displays a loading spinner when loading is true.
  • Message: Displays "Click on the button to fetch news" if no news is fetched yet.
  • Error Message: Displays an error message if the API request fails.
  • News Container: Displays the fetched news article's author and title.
  • Button: Triggers the fetchNews function when pressed.

Styling

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    height: 300,
    width: 300,
  },
  loading: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  message: {
    fontSize: 20,
  },
  error: {
    fontSize: 20,
    color: 'red',
  },
  newsContainer: {
    alignItems: 'center',
    flex: 1,
    justifyContent: 'center',
    backgroundColor: 'blue',
    padding: 20,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: 'black',
    marginTop: 10,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  description: {
    fontSize: 18,
    color: 'black',
  },
  dataContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    width: 300,
    height: 300,
    marginTop: 10,
  },
  button: {
    marginTop: 10,
  },
});
  • container: Centers the content and restricts the view size to 300x300.
  • loading: Centers the ActivityIndicator over the entire screen.
  • message: Styles the initial message text.
  • error: Styles the error message in red.
  • newsContainer: Styles the news container with centered content, padding, and a blue background.
  • title and description: Styles for the news title and description text.
  • dataContainer: Centers and contains the fetched news and button.

Exporting the Component

export default Homepage;
  • Exports the Homepage component as the default export so it can be used in other parts of the application. After making this page I imported it into my app page like this, app page in react and react native works similar as it abstracts the main index.js file which runs the whole application.

This code sets up the main entry point for a React Native application. It imports and uses a Homepage component within a scrollable view, applying specific styles to position and center the content.

Imports

import { View, Text, ScrollView, StyleSheet } from 'react-native';
import React from 'react';
import Homepage from './Pages/Homepage';
  • View, Text, ScrollView, StyleSheet: Core components and utilities from React Native.
    • View: A container component that can hold other components.
    • Text: A component for displaying text.
    • ScrollView: A container that allows you to scroll through its child components if they exceed the screen size.
    • StyleSheet: A utility for defining component styles in a clean, organized way.
  • React: The core library for building user interfaces.
  • Homepage: A custom component that is imported from a local file (./Pages/Homepage).

App Component

const App = () => {
  return (
    <ScrollView>
      <View style={styles.container}>
        <Homepage />
      </View>
    </ScrollView>
  );
};
  • App: A functional component that serves as the root component of the application.
  • ScrollView: Wraps the content of the app in a scrollable container, which is useful if the content exceeds the screen height. This allows users to scroll to view all content.
  • View: A container that holds the Homepage component. The View is styled using the styles.container object.
  • Homepage: The custom component imported earlier, which is rendered inside the View.

Styles

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    height: 300,
    width: 300,
    marginTop: 300,
    marginLeft: 50,
  },
});
  • container: An object containing styles applied to the View component wrapping the Homepage component.
    • flex: 1: Makes the container take up the available space on the screen.
    • justifyContent: 'center': Vertically centers the content within the View.
    • alignItems: 'center': Horizontally centers the content within the View.
    • height: 300: Sets the height of the View to 300 units.
    • width: 300: Sets the width of the View to 300 units.
    • marginTop: 300: Adds 300 units of space above the View.
    • marginLeft: 50: Adds 50 units of space to the left of the View.

Exporting the Component

export default App;
  • Exports the App component as the default export so it can be used as the main entry point of the application.

Here is what our final app looks like

Build you app

Now our app is ready but we have finally build our first android app using React Native without expo ,Its time to get the fascinated apk file so that you can install and distribute your app easily .

To achieve this simply run this command in your android folder

First navigate to the android folder of your project

Run this command :./gradlew assembleRelease

It will generate an apk file into your android folder.

You can find the apk into the build folder of android folder inside outputs<apk<release as we have used relase command to build the apk .

here is the snippet :

Image description

Summary

  • The App component uses a ScrollView to ensure that if the content overflows the screen height, it can be scrolled.
  • The Homepage component is placed within a View that is centered on the screen with specific height, width, and margins.
  • The styles.container object defines how the View should be styled, including its position and dimensions.

This setup provides a simple and structured way to display the Homepage component in a scrollable, centered manner.

Final Screens:

The final screens are out here as you can see when we click on fetch news buttons we get a news and its author and when we don't have any news to display its ask us to click on news button to fetch news.

Image description

Image description

Conclusion

Building anything is easy if know what tools to use and how to use them ,When I build my first react native app it took me 15 days to navigate to through various errors but I didn't give up and troubleshooted everything resulted in successful android build.
This app is very simple but no matter how complex apps you are building the fundamentals are always be same.

If you need source code ping me .
Thanks for reading ...!
Keep coding...

💖 💪 🙅 🚩
prankurpandeyy
PRANKUR PANDEY

Posted on September 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related