Android Dev

Methods to Construct an Android Information App with React Native and Native Base

By Nishant Kumar

We reside in a world the place issues are consistently altering. So if you wish to keep updated on what’s taking place, you will desire a good Information app.

That can assist you study some cool tech and keep present, on this weblog submit we’ll construct a Information Software for Android utilizing React Native. It would fetch headlines from completely different information channels and present them by class.

Image

That is how our app will look after we’re performed. So let’s bounce proper into it.

Methods to Set up Expo

So, what’s Expo? Expo is a framework that helps you construct and deploy a React Native app rapidly and simply.

Let’s set up it.

npm set up --world expo-cli

Run this command in your terminal to put in the Expo CLI. Right here, we’re utilizing --global to ensure it installs in every single place.

After it has been put in, we have to create an Expo Challenge.

expo init Information-Software

Use the above command to initialize the challenge. It would ask you a number of questions, just like the title of your software, whether or not you need add TypeScript in your challenge, or begin with a clean challenge. Simply choose clean, and press enter.

Then, it can obtain all of the packages and dependencies within the folder.

Now, after that is performed, navigate into the challenge folder. To begin the applying, kind expo begin. It would open up developer instruments within the browser.

Image
Expo developer instruments

Right here you will see many choices on the left, like run on Android gadget/emulator, or on iOS simulator. We are going to run the applying on the Internet Browser, so click on the Run in Internet Browser possibility.

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Textual content, View } from 'react-native';

export default operate App() {
  return (
    <View type={kinds.container}>
      <Textual content>Open up App.js to begin working in your app!</Textual content>
      <StatusBar type="auto" />
    </View>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'heart',
    justifyContent: 'heart',
  },
});

That is our App.js file, which accommodates the default boilerplate.

Image
Our output

Now our software is working.

Methods to Create Completely different Screens utilizing React Navigation

Now, let’s create numerous completely different screens for our software. For that, we’ll use React Navigation. So, let’s set up it.

Head to https://reactnavigation.org/ and click on Learn Docs. It would open up the documentation web page.

Let’s set up React Navigation by utilizing the command beneath:

npm set up @react-navigation/native

expo set up react-native-screens react-native-safe-area-context

Now, our React Navigation has been put in.

We are going to use bottomTabNavigator. So, from the left menu, select API Reference, then Navigators, then the Backside Tabs.

Image
Select Backside Tabs

Let’s set up the Backside Tabs utilizing the command beneath:

npm set up @react-navigation/bottom-tabs

Now, in our App.js file, we have to import Backside Tabs so as to use it.

So, import it like this:

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

Now, let’s import the Tab Screens.

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { NavigationContainer } from '@react-navigation/native';
const Tab = createBottomTabNavigator();

operate MyTabs() {
  return (
    <Tab.Navigator>
      <Tab.Display title="Dwelling" element={HomeScreen} />
      <Tab.Display title="Settings" element={SettingsScreen} />
    </Tab.Navigator>
  );
}

That is how we create Backside Tabs.

In our case, we have to do one thing like this:

<Tab.Navigator>
  <Tab.Display title="All" element={All} />
  <Tab.Display title="Enterprise" element={Enterprise} />
  <Tab.Display title="Well being" element={HealthScreen} />
  <Tab.Display title="Sports activities" element={SportsScreen} />
  <Tab.Display title="Tech" element={TechScreen} />
</Tab.Navigator>

We have to create these screens for the next tabs: All Information, Enterprise Information, Sports activities Information, Well being Information, and the Tech Information. Additionally, create one element within the Challenge for every display.

We have to wrap this TabNavigtor right into a NavigationContainer like this:

<NavigationContainer>
  <Tab.Navigator>
    <Tab.Display title="All" element={All} />
    <Tab.Display title="Enterprise" element={Enterprise} />
    <Tab.Display title="Well being" element={HealthScreen} />
    <Tab.Display title="Sports activities" element={SportsScreen} />
    <Tab.Display title="Tech" element={TechScreen} />
  </Tab.Navigator>
</NavigationContainer>

We additionally have to import these all parts, so import them on the high.

import All from './screens/All';
import Enterprise from './screens/Enterprise';
import HealthScreen from './screens/Well being';
import SportsScreen from './screens/Sports activities';
import TechScreen from './screens/Tech';

Now, if we put all of the code collectively that now we have written, we’ll get the beneath code:

import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { NavigationContainer } from '@react-navigation/native';
import All from './screens/All';
import Enterprise from './screens/Enterprise';
import HealthScreen from './screens/Well being';
import SportsScreen from './screens/Sports activities';
import TechScreen from './screens/Tech';
const Tab = createBottomTabNavigator();

export default operate App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Display title="All" element={All} />
        <Tab.Display title="Enterprise" element={Enterprise} />
        <Tab.Display title="Well being" element={HealthScreen} />
        <Tab.Display title="Sports activities" element={SportsScreen} />
        <Tab.Display title="Tech" element={TechScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

And this might be our output:

Image
Our 5 screens specifically All, Enterprise, Well being, Sports activities and Tech

We’ve 5 screens right here for All, Enterprise, Well being, Sports activities and Tech.

Now, let’s make a number of changes right here. We have to change the icons for the underside tabs.

To try this, we’ll have to get an icon library for our icons. For that we’re going to use react-native-elements.

To put in it, kind the beneath command:

npm set up react-native-elements

This icon bundle has numerous icon choices to select from.

Image
Obtainable Icons in React Native Parts

Now let’s add our icons within the Backside Tab Navigator.

<Tab.Display title="All" element={All}
          choices={{
            tabBarIcon: (props) => (
              <Icon kind='feather' title='house' coloration={props.coloration} />
            ),
          }} />

Right here now we have added the icon named “house” for the house web page and feather icon class for kind.

Image
Backside Tab Navigator with the Dwelling Icon

This may yield the above output. And equally, let’s repeat the identical course of for all of them.

<Tab.Navigator>
        <Tab.Display title="All" element={All}
          choices={{
            tabBarIcon: (props) => (
              <Icon kind='feather' title='house' coloration={props.coloration} />
            ),
          }} />

        <Tab.Display title="Enterprise" element={Enterprise}
          choices={{
            tabBarIcon: (props) => (
              <Icon kind='feather' title='dollar-sign' coloration={props.coloration} />
            ),
          }} />

        <Tab.Display title="Well being" element={HealthScreen}
          choices={{
            tabBarIcon: (props) => (
              <Icon kind='feather' title='coronary heart' coloration={props.coloration} />
            ),
          }} />

        <Tab.Display title="Sports activities" element={SportsScreen}
          choices={{
            tabBarIcon: (props) => (
              <Icon kind='ionicon' title="tennisball-outline" coloration={props.coloration} />
            ),
          }} />

        <Tab.Display title="Tech" element={TechScreen}
          choices={{
            tabBarIcon: (props) => (
              <Icon kind='ionicon' title="hardware-chip-outline" coloration={props.coloration} />
            ),
          }} />
      </Tab.Navigator>

Image

Now every of our completely different tabs or screens are performed, and so they every have their very own distinct icon.

Methods to Name the Information API

Now, let’s name the Information API from https://newsapi.org/

Image

Go to this web site and signup. It will provide you with an API key.

We’d like a config file to retailer all of the Information constants, so let’s create it.

export const API_KEY = ``;
export const endpoint = `https://newsapi.org/v2/top-headlines`;
export const nation = 'in'

We’d like the API_KEY, the endpoint, and the nation code.

Now, we have to create a service for our GET API Request.

Create a file known as providers.js.

Right here, import API_KEY, endpoint, and the nation on the high.

import { API_KEY, endpoint, nation } from '../config/config';

Then, we’ll write our providers physique.

export async operate providers(class = 'normal') {
    let articles = await fetch(`${endpoint}?nation=${nation}&class=${class}`, {
        headers: {
            'X-API-KEY': API_KEY
        }
    });

    let end result = await articles.json();
    articles = null;

    return end result.articles;
}

So, we’re fetching the information knowledge by utilizing our endpoint, and appending the nation and the class. Within the operate, we go the class as normal as a result of that’s the default class. We additionally go the API_key within the headers.

Then, we convert the response, or incoming knowledge, into JSON format and storing it in a end result variable.

And lastly, we’re returning it utilizing the return key phrase.

This is the entire file in your reference:

import { API_KEY, endpoint, nation } from '../config/config';

export async operate providers(class = 'normal') {
    let articles = await fetch(`${endpoint}?nation=${nation}&class=${class}`, {
        headers: {
            'X-API-KEY': API_KEY
        }
    });

    let end result = await articles.json();
    articles = null;

    return end result.articles;
}

Now, we have to import this service into our All.js file.

import { providers } from '../providers/providers';

We might want to use the useState and useEffect hooks. The useEffect hook will name this service throughout the All.js file and useState will create a state that may retailer the response coming from the API.

import React, { useEffect, useState } from 'react'
import { View } from 'react-native';
import { providers } from '../providers/providers';
export default operate All() {
    const [newsData, setNewsData] = useState([])
    useEffect(() => {
        providers('normal')
            .then(knowledge => {
                setNewsData(knowledge)
            })
            .catch(error => {
                alert(error)
            })
    }, [])
    return (
        <View>

        </View>
    )
}

On this file, we name the providers in our useEffect hook. After which we retailer the response within the newsData state, which is an array. We additionally go a parameter for the class which is normal.

This display will fetch all information, so we use the overall class. It would change for each different display. It will likely be well being for the Well being display, sports activities for Sports activities, and so forth.

Now, we have to present this knowledge in our interface. And for that, we want yet one more bundle known as Native Base. So, let’s set up it.

Sort the instructions beneath to put in Native Base:

yarn add native-base styled-components styled-system
expo set up react-native-svg react-native-safe-area-context

In All.js, let’s import a number of issues from Native Base:

import React, { useEffect, useState } from 'react'
import { View, Textual content } from 'react-native';
import { NativeBaseProvider, FlatList, ScrollView, Divider, Picture, Spinner } from 'native-base';
import { providers } from '../providers/providers';

Then within the return, we’ll add NativeBaseProvider.

return (
        <NativeBaseProvider>

        </NativeBaseProvider>
    )

Then, let’s add the Scroll View. This may let customers scroll if the information knowledge goes past our display top.

<NativeBaseProvider>
            <ScrollView top={850}>

            </ScrollView>
        </NativeBaseProvider>

Now, let’s add the FlatList to point out our information knowledge.

<NativeBaseProvider>
            <ScrollView top={850}>
                <FlatList
                    knowledge={newsData}
                    renderItem={({ merchandise }) => (
                       <View>

                       </View> 
                    )}
                    keyExtractor={(merchandise) => merchandise.id}
                />
            </ScrollView>
        </NativeBaseProvider>

The FlatList takes a knowledge prop, which is our newsData state that we created earlier, and it returns an merchandise from renderItems.

That is much like map in JavaScript, which traverses over an array and returns an merchandise. It additionally has a keyExtractor which we use to make every merchandise distinctive.

Now, let’s present our knowledge within the View.

Create another view contained in the mum or dad view like this:

<NativeBaseProvider>
            <ScrollView top={850}>
                <FlatList
                    knowledge={newsData}
                    renderItem={({ merchandise }) => (
                       <View>
                           <View>

                           </View>
                       </View> 
                    )}
                    keyExtractor={(merchandise) => merchandise.id}
                />
            </ScrollView>
        </NativeBaseProvider>

Now, let’s add some textual content contained in the little one view.

<NativeBaseProvider>
            <ScrollView top={850}>
                <FlatList
                    knowledge={newsData}
                    renderItem={({ merchandise }) => (
                        <View>
                            <View>
                                <Textual content>
                                    {merchandise.title}
                                </Textual content>
                                <Textual content>
                                    {merchandise.publishedAt}
                                </Textual content>
                                <Textual content>
                                    {merchandise.description}
                                </Textual content>
                            </View>
                        </View>
                    )}
                    keyExtractor={(merchandise) => merchandise.id}
                />
            </ScrollView>
        </NativeBaseProvider>

This accommodates our information headline title, the outline, and the revealed date.

Image

Methods to Fashion our React Native Information App

That is how our app seems to be now, with information title, description, and the date. To make it look a bit nicer, we have to give it some styling.

Import StyleSheet from React Native on the high so as to use its styling.

import { View, Textual content, StyleSheet } from 'react-native';
<View>
                            <View type={kinds.newsContainer}>
                                <Textual content type={kinds.title}>
                                    {merchandise.title}
                                </Textual content>
                                <Textual content type={kinds.date}>
                                    {merchandise.publishedAt}
                                </Textual content>
                                <Textual content type={kinds.newsDescription}>
                                    {merchandise.description}
                                </Textual content>
                            </View>
                        </View>

Then, add kinds like this. And on the backside we have to create these kinds.

const kinds = StyleSheet.create({
    newsContainer: {
        padding: 10
    },
    title: {
        fontSize: 18,
        marginTop: 10,
        fontWeight: "600"
    },
    newsDescription: {
        fontSize: 16,
        marginTop: 10
    },
    date: {
        fontSize: 14
    },
});

Image

That is how the applying seems to be now after getting some styling. You may also scroll down the web page.

Now, we have to change the date format to a readable format, as a result of I do not perceive ‘2021-08-21T11:00:40Z’.

We’ll use the useful second.js bundle for that, so let’s set up it utilizing the command beneath:

npm set up second --save

Then, import it in our All.js display:

<Textual content type={kinds.date}>
  {second(merchandise.publishedAt).format('LLL')}
</Textual content>

Format the date like this:

Image
Second.js time and date codecs

The second documentation provides us so many codecs to select from. I’ve chosen the ‘LLL’ format.

Image

And now our dates are rather more human-readable.

We additionally want a divider to separate the information articles from one another so they do not all run collectively.

<View>
                            <View type={kinds.newsContainer}>
                                <Textual content type={kinds.title}>
                                    {merchandise.title}
                                </Textual content>
                                <Textual content type={kinds.date}>
                                    {second(merchandise.publishedAt).format('LLL')}
                                </Textual content>
                                <Textual content type={kinds.newsDescription}>
                                    {merchandise.description}
                                </Textual content>
                            </View>
                            <Divider my={2} bg="#e0e0e0" />
                        </View>

So, after including a divider after the kid view, our app seems to be like this:

Image

Now our information headlines are divided which seems to be nice.

This Information API has a picture too. So, let’s add it.

<View>
                            <View type={kinds.newsContainer}>
                                <Picture
                                    width={550}
                                    top={250}
                                    resizeMode={"cowl"}
                                    supply={{
                                        uri: merchandise.urlToImage,
                                    }}
                                    alt="Alternate Textual content"
                                />
                                <Textual content type={kinds.title}>
                                    {merchandise.title}
                                </Textual content>
                                <Textual content type={kinds.date}>
                                    {second(merchandise.publishedAt).format('LLL')}
                                </Textual content>
                                <Textual content type={kinds.newsDescription}>
                                    {merchandise.description}
                                </Textual content>
                            </View>
                            <Divider my={2} bg="#e0e0e0" />
                        </View>

So, now we have added the picture and we used the important thing known as urlToImage to do that.

Image

Now now we have the information pictures exhibiting up.

Methods to Add a Spinner to Present Information Loading

Let’s add a spinner that may present when the information is loading.

First, we’ll create a examine. If the newsData state’s size is multiple, we’ll present our FlatList, which accommodates our information knowledge. In any other case we’ll present the loading spinner.

In different phrases, if the newsData state’s size is lower than one, it means it’s empty and the API remains to be getting known as. As soon as the API name finishes, it can retailer the info into the newsData state, and the state’s size will change to multiple.

{newsData.size > 1 ? (
                    <FlatList
                        knowledge={newsData}
                        renderItem={({ merchandise }) => (
                            <View>
                                <View type={kinds.newsContainer}>
                                    <Picture
                                        width={550}
                                        top={250}
                                        resizeMode={"cowl"}
                                        supply={{
                                            uri: merchandise.urlToImage,
                                        }}
                                        alt="Alternate Textual content"
                                    />
                                    <Textual content type={kinds.title}>
                                        {merchandise.title}
                                    </Textual content>
                                    <Textual content type={kinds.date}>
                                        {second(merchandise.publishedAt).format('LLL')}
                                    </Textual content>
                                    <Textual content type={kinds.newsDescription}>
                                        {merchandise.description}
                                    </Textual content>
                                </View>
                                <Divider my={2} bg="#e0e0e0" />
                            </View>
                        )}
                        keyExtractor={(merchandise) => merchandise.id}
                    />
                ) : (
                    <View type={kinds.spinner}>
                        <Spinner coloration="hazard.400" />
                    </View>
                )}

And in our kinds, add the beneath type code for the spinner.

spinner: {
        show: 'flex',
        justifyContent: 'heart',
        alignItems: 'heart',
        top: 400
}

Right here is the code beneath in your reference:

import React, { useEffect, useState } from 'react'
import { View, Textual content, StyleSheet } from 'react-native';
import { NativeBaseProvider, FlatList, ScrollView, Divider, Picture, Spinner } from 'native-base';
import { providers } from '../providers/providers';
import second from 'second'
export default operate All() {
    const [newsData, setNewsData] = useState([])
    useEffect(() => {
        providers('normal')
            .then(knowledge => {
                setNewsData(knowledge)
            })
            .catch(error => {
                alert(error)
            })
    }, [])
    return (
        <NativeBaseProvider>
            <ScrollView top={850}>
                {newsData.size > 1 ? (
                    <FlatList
                        knowledge={newsData}
                        renderItem={({ merchandise }) => (
                            <View>
                                <View type={kinds.newsContainer}>
                                    <Picture
                                        width={550}
                                        top={250}
                                        resizeMode={"cowl"}
                                        supply={{
                                            uri: merchandise.urlToImage,
                                        }}
                                        alt="Alternate Textual content"
                                    />
                                    <Textual content type={kinds.title}>
                                        {merchandise.title}
                                    </Textual content>
                                    <Textual content type={kinds.date}>
                                        {second(merchandise.publishedAt).format('LLL')}
                                    </Textual content>
                                    <Textual content type={kinds.newsDescription}>
                                        {merchandise.description}
                                    </Textual content>
                                </View>
                                <Divider my={2} bg="#e0e0e0" />
                            </View>
                        )}
                        keyExtractor={(merchandise) => merchandise.id}
                    />
                ) : (
                    <View type={kinds.spinner}>
                        <Spinner coloration="hazard.400" />
                    </View>
                )}
            </ScrollView>
        </NativeBaseProvider>
    )
}

const kinds = StyleSheet.create({
    newsContainer: {
        padding: 10
    },
    title: {
        fontSize: 18,
        marginTop: 10,
        fontWeight: "600"
    },
    newsDescription: {
        fontSize: 16,
        marginTop: 10
    },
    date: {
        fontSize: 14
    },
    spinner: {
        show: 'flex',
        justifyContent: 'heart',
        alignItems: 'heart',
        top: 400
    }
});

Our All.js display is now full.

And now, we will use the identical code in all different screens as effectively. We simply want to vary the parameter we’re passing within the providers within the useEffect Hook.

So, for the Enterprise display, we’ll use enterprise. For Well being, we’ll use well being, and so forth.

import React, { useEffect, useState } from 'react'
import { View, Textual content, StyleSheet } from 'react-native';
import { NativeBaseProvider, FlatList, ScrollView, Divider, Picture, Spinner } from 'native-base';
import { providers } from '../providers/providers';
import second from 'second'
export default operate Enterprise() {
    const [newsData, setNewsData] = useState([])
    useEffect(() => {
        providers('enterprise')
            .then(knowledge => {
                setNewsData(knowledge)
            })
            .catch(error => {
                alert(error)
            })
    }, [])
    return (
        <NativeBaseProvider>
            <ScrollView top={850}>
                {newsData.size > 1 ? (
                    <FlatList
                        knowledge={newsData}
                        renderItem={({ merchandise }) => (
                            <View>
                                <View type={kinds.newsContainer}>
                                    <Picture
                                        width={550}
                                        top={250}
                                        resizeMode={"cowl"}
                                        supply={{
                                            uri: merchandise.urlToImage,
                                        }}
                                        alt="Alternate Textual content"
                                    />
                                    <Textual content type={kinds.title}>
                                        {merchandise.title}
                                    </Textual content>
                                    <Textual content type={kinds.date}>
                                        {second(merchandise.publishedAt).format('LLL')}
                                    </Textual content>
                                    <Textual content type={kinds.newsDescription}>
                                        {merchandise.description}
                                    </Textual content>
                                </View>
                                <Divider my={2} bg="#e0e0e0" />
                            </View>
                        )}
                        keyExtractor={(merchandise) => merchandise.id}
                    />
                ) : (
                    <View type={kinds.spinner}>
                        <Spinner coloration="hazard.400" />
                    </View>
                )}
            </ScrollView>
        </NativeBaseProvider>
    )
}

const kinds = StyleSheet.create({
    newsContainer: {
        padding: 10
    },
    title: {
        fontSize: 18,
        marginTop: 10,
        fontWeight: "600"
    },
    newsDescription: {
        fontSize: 16,
        marginTop: 10
    },
    date: {
        fontSize: 14
    },
    spinner: {
        show: 'flex',
        justifyContent: 'heart',
        alignItems: 'heart',
        top: 400
    }
});

Image

Scroll down the Enterprise Display, and you will note the information associated to Enterprise.

And you are able to do the identical for all the opposite screens:

useEffect(() => {
        providers('enterprise')
            .then(knowledge => {
                setNewsData(knowledge)
            })
            .catch(error => {
                alert(error)
            })
}, [])
useEffect(() => {
        providers('well being')
            .then(knowledge => {
                setNewsData(knowledge)
            })
            .catch(error => {
                alert(error)
            })
    }, [])
useEffect(() => {
        providers('sports activities')
            .then(knowledge => {
                setNewsData(knowledge)
            })
            .catch(error => {
                alert(error)
            })
    }, [])
useEffect(() => {
        providers('expertise')
            .then(knowledge => {
                setNewsData(knowledge)
            })
            .catch(error => {
                alert(error)
            })
    }, [])

Conclusion

Congratulations! Now our information software is full.

So go forward, construct and experiment with it a bit. There are tons of issues you are able to do.

You’ll be able to take a look at my playlist on Build a News Application using React Native and Native Base, which is on my YouTube channel.

Be at liberty to obtain the code right here: https://github.com/nishant-666/React-Native-News

Pleased Studying.

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button

Adblock Detected

Please consider supporting us by disabling your ad blocker