0% found this document useful (0 votes)
110 views

Master ReactJS Part 2 MFurqan Riaz

Uploaded by

cauliflowers33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Master ReactJS Part 2 MFurqan Riaz

Uploaded by

cauliflowers33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

© Copyright 2022 M.

Furqan - All rights


reserved.

The content in this book may not be reproduced,


duplicated, or transmitted without direct written
permission from the author or publisher.

Under no circumstance will any blame or legal


responsibility be held against the publisher, or
author, for any damages, reparation, or monetary
loss due to the information contained within this
book. Either directly or indirectly. You are responsible
for your own choices, actions, and results.

Legal Notice:

This book is copyright protected. This book is only for


personal use. You cannot amend, distribute, sell, use,
quote, or paraphrase any part, or the content within
this book, without the consent of the author or
publisher.

Disclaimer Notice:

Please note the information contained within this


document is for educational and entertainment
purposes only. All effort has been executed to present
accurate, Up to date, and reliable, complete
information. No warranties of any kind are declared
or implied. Readers acknowledge that the author is
not engaging in the rendering of legal, financial,
medical, or professional advice. Please consult a
licensed professional before attempting any
techniques outlined in this book.

By reading this document, the reader agrees that

under no circumstances is the author responsible for

any losses, direct or indirect, which are incurred as a

result of the use of the information contained within

this document, including, but not limited to errors,

omissions, inaccuracies .

OceanofPDF.com
[Free] Building + Hosting React App For free on Github
Pages | Complete React Course Article #17
Purchasing a Domain + Hosting TextUtils on a VPS |
Complete React Course Article #18
Fixing Issues & Wrapping up TextUtils | Complete React
Course Article #19
Exercise 2: Solutions + Shoutouts | Complete React Course
Article #20
fixing few more Textutils Issues | Complete React Course
Article #21
Project 2 Setup + Introduction to Class based components |
Complete React Course Article #22
Component Structure of our NewsMonkey React App |
Complete React Course Article #23
Fetching API Key from News API | Complete React Course
Article #24
Understanding state in class based components | Complete
React Course Article #25
Looping through an array in JSX to display NewsItems from
state | Complete React Course Article #26
Using Fetch API in React to populate NewsItems | Complete
React Course Article #27
Adding Previous & Next Buttons to populate NewsItems |
Complete React Course Article #28
Adding loading spinner & variable pageSize to NewsMonkey
| Complete React Course Article #29
Adding Categories & propTypes to NewsMonkey React App |
Complete React Course Article #30
Fetching News category wise in NewsMonkey React App |
Complete React Course Article #31
Adding time, author and news source to News React App |
Complete React Course Article #32

OceanofPDF.com
[Free] Building + Hosting
React App For free on
Github Pages | Complete
React Course Article #17
At this moment, we have created our React application and
would like to host our application in Github for free.
You can install Git and Github from their official sites,
respectively.
Deploying TextUtils
Whenever we create our application for production, we build
it using the npm run build command and not by using npm
start.

npm run build: npm run build bundles the app into static
files for production, i.e. it creates a build folder that contains
your application as a static application.
In Build Folder:

If you open your build folder in the live server, you will find
that your application is working perfectly, which means our
application is being converted into static files for
deployment.
Note: React Router doesn’t work perfectly with Github
pages, so we are going to remove the router from our
application. But remember that while deploying in the
server, it runs perfectly.
Deploying a Normal Application
For deploying a normal application, you have to just go to
the settings section of GitHub and then navigate to the
pages tab, where you can select the branch and root of your
app and can easily deploy your application. But while
hosting a react application, you have to follow a different set
of steps, which are mentioned below:
Steps for Hosting our React Application:
1. Add the Home page field:
You can add the homepage field in your application by
Copying the below code in your package.json.
"homepage": "https://myusername.github.io/my-app",
Make sure to enter your username and the correct name of
your application in the mentioned places in the above URL.
2. Install gh-pages
Use the below command to install gh-pages in your React
app.
npm install --save gh-pages

3. Add the script in "package.json"


Add the below code in the script (available in
"package.json") of your React application.

"predeploy": "npm run build",


"deploy": "gh-pages -d build",

4. Run the npm run deploy


Using the npm run deploy command in your terminal will
begin the publishing process.
After a certain time, the Github login dialog box appears.
Enter your GitHub username and password and login into
your account.

Hence our application has been hosted on Github.

If you are facing any problem, then check out the pages
section available in settings, and make sure to select the
branch as gh-pages as shown below:

Our TextUtils application:


In a nutshell:
Here is the short summary of the four steps, which are
required for deploying your application in Github:

Figure 1.2: Hosting the application in Github

So here we completed the 17th article of this React series.


In the upcoming articles, we will be covering a lot of new
concepts of React with some new projects that would allow
you to understand React completely.

Do remember to Access the playlist of the Free React Course


in Hindi by clicking here.
Thank you for being with me throughout the article. In the
next article, we will purchase a domain and host TextUtils on
a VPS. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Purchasing a Domain +
Hosting TextUtils on a VPS
| Complete React Course
Article #18
In the last tutorial, we hosted our application on github for
free. Today we are going to host our application on a paid
hosting server. So without further ado let’s begin!
Enable Router and "about.js"
Earlier, we have commented out our router and "about.js".
So firstly recover the Router and the about page again,
because this time we are going to host our application on a
paid server and not on Github.
Uninstalling gh-pages
We want to deploy our application in normal hosting and not
in Github so remove the homepage from "package.json".
Also, we will uninstall gh-pages by using the "npm uninstall
gh-pages" command.
npm run build
We would be using the npm run build command, instead of
npm start, because we are building the application for
production.
Hosting - Digital Ocean
We will be hosting our application in Digital Ocean. You can
host your application on any other hosting provider as well.
Creating Droplet
To create a droplet, click on the top right create button and
select droplet, or to use your previous droplet click on the
destroy section and then select the rebuild droplet option to
use your previously created droplet.
Reset New password
Open your Windows Powershell and write ssh root@ and
paste your IPv4 address. You will receive your new password
in your email ID.
Installing nginx
The next thing which we have to do is to install nginx, Follow
the below steps to install nginx:
1. Firstly run the apt update by using the below command:

sudo apt update

2. After that install nginx by using the below command:

sudo apt install nginx

Now, visit the server IP address, which is your IPv4 address,


to check if nginx has been installed or not.

Using Filezilla
Enter your host, username and password in FileZilla and
then navigate to "/var/www" and delete the existing file and
at last copy your build folder and paste it in there.
Figure 1.1: Using Filezilla

Now our static React app has been hosted on an IP address


(Your ipv4 address).

Purchasing a Domain
We would be purchasing the domain from Go Daddy. Our
desired domain is mytextUtils.com, Therefore we have
purchased it for two years at a price of Rs.1504.
DNS management
A record will be added to our DNS. In the ‘points to’ field, we
will be copying our IP address and then save the settings.
After a while, our website will be live at mytextutils.com

Hence we have successfully hosted our application and


have purchased a professional domain for it.
Our application
In the end, Our application has been hosted on digital ocean
and has got the professional domain, which is
mytextutils.com.
Figure 1.2: Our application

So here we complete the 18th article of this React series. In


the upcoming articles, we will be covering a lot of new
concepts of React with some amazing projects that would
allow you to understand React completely.
Thank you for being with me throughout the article. In the
next article we will fix issues & wrap up TextUtils. Till then,
Keep learning and Keep Coding.

OceanofPDF.com
Fixing Issues & Wrapping
up TextUtils | Complete
React Course Article #19
Earlier, we created our Textutils application. To check out
our app, visit mytextutils.com. In this article, we are going
to enhance our TextUtils application by fixing some issues.
Here are some of the issues in our TextUtils application:
1. Word Counting Error
2. No Mobile friendly buttons
3. No Relevant About Text
4. The layout is shifting when an alert appears (while
clicking a button)
5. The cursor is invisible in Dark mode
6. Expected Reading Time Error
7. No SEO optimization
8. Buttons are still working when the textbox is blank.
9. No SSL due to which the ‘copy Text’ button isn’t
working
10. Deselecting the Copied Text
So let’s start our application in localhost and begin solving
these issues one by one:
1. Word Counting Error
We have created the function of Counting words in our
Textform.js. The split() method is used to convert the string
into an array. In our case, We are splitting the string by a
space and then counting the length of that array, which
comes out to be one. Therefore, a blank space is being
counted as a word.

Solution: The quick way of fixing this error is by removing


the empty strings from the split array. We can easily do so
by using the filter method in our Text.split function as
described below:
{text.split(" ").filter((element)=>{return
element.length!==0}).length}

If the arrow function returns the true value for an element,


then only it would be allowed to stay in the split array. The
filter() does not execute the function for empty array
elements.
Our Error has been Successfully Resolved.
2. Adding Mobile-Friendly Buttons
Figure 1.1: No Mobile-Friendly Buttons

The above error is occurring as there is no margin for the


buttons in the Y direction. To solve this issue add some
margin to the buttons, available in "textform.js", in the Y
direction. Our Error has been successfully resolved.
3. Enhancing "about.js"
Figure 1.2: Unfavourable About Page

We would remove the Dark mode button of the Accordion


and also the ToggleStyle function assigned to it from
about.js. We are adding our desired text in Accordion and
editing it in our own way.

Adding a proper Dark Mode to about.js


To add dark mode to our about.js, follow the below steps.
Step 1: Firstly, Pass Mode in About component of App.js as
<About mode={mode}/>

Step 2: We would create a new ‘myStyle’ variable which


would provide our desired design to the About page, on
enabling the dark mode.

let myStyle = {
color: props.mode === 'dark'?'white':'#042743',
backgroundColor: props.mode ==='dark'?'rgb(36 74
104)':'white'
}

Step 3: We have used conditional operators to set color


while changing modes. After that, we would pass this
"myStyle" to the Accordion component, and We would only
pass the color to the heading because we would like to
differentiate the heading from the rest of the component.
You can use any of your desired colors to style the
components.

Figure 1.3: About Page of our Application


We have successfully enhanced our About Page
4. Layout Shifting Issue
The layout of our application is shifting when an alert is
shown. Remember that the layout shift must be minimum
for your application, as this is one of the ranking factors
from the SEO point of view.

Solution: To resolve the issue, go to your "alert.js", and


inside the alert component, we would wrap the alert inside a
div container having a specific height.

Figure 1.4: Solving CLS issue

As a result, the Alert component will have a specific height


for its display, and hence it would not shift the layout.

Our CLS Error has been successfully resolved.


5. Cursor Invisibility in Dark Mode
Our cursor is becoming invisible on hovering in the textbox
due to its grey color. To solve this problem, simply change
the color of the "textarea" from grey to blue. We can easily
do that by going to the textarea in "textform.js" and editing
its existing style.

Figure 1.5: Solving Cursor Invisibility


Our cursor is visible in the dark mode.
6. Expected Reading Time Error
Our application will be showing the expected time to read
the provided text, but if the Textbox is blank then also our
Time counter is showing an expected time to read the text.
To fix this bug in our application, we would use the filter
method as we have used to solve the counting word error.
<p>{0.008 * text.split(" ").filter((element)=>{return
element.length!==0}).length} Minute read </p>

Our Reading Time Error has been successfully resolved.


7. Fixing for SEO
SEO is one of the factors which helps our website to rank on
Google. To make our application SEO optimized we would
make the following changes to our Index.html and
Textform.js:
In index.html:

Meta Description: It provides a brief sketch of the content


of the website to the Google crawler. Therefore, it becomes
utterly important to add specific keywords related to our
content in the meta description.

Title: It specifies the Content of our specific web pages.


Hence, we have changed the title of our application by
adding some relevant Keywords to it.

Figure 1.6: Adding Meta Description and Title

In textform.js:

Editing Headings: It plays a major role in the SEO


optimization of our website as it makes it easier for a User
and Crawler to navigate through the page. We will be
passing a new heading, having relevant keywords related to
our application, in props.heading from app.js.

Figure 1.7: Passing New Heading


We have optimized our app for search engines.
8. Disable button
When our Textbox is empty, but our buttons are working and
performing their functions, which seems like a bug to our
application,
Solution: To overcome this issue, we would add the below
code to every button.
disabled={text.length===0}

This code means to disable the buttons when the length of


the text is 0. That is, the textbox is empty.
Error has been successfully resolved.
9. Enabling HTTPS
The copy text button of TextUtils isn’t working as we don’t
have https. To enable https for our application, simply run
the following commands in Git Bash or any other terminal.
1. Install Certbot
sudo apt-get install certbot

2. Certbot Nginx
apt-get install python3-certbot-nginx

3. Verifying the Syntax and Restarting Nginx


nginx -t && nginx -s reload

4. Obtain the SSL certificate


sudo certbot --nginx -d mytextutils.com -d
www.mytextutils.com

Make sure to run this command for your domain. We have


used it for our mytextutils.com domain.
5. After that, fill up some details like entering your Email
and select your favorable options.
HTTPS has been Enabled for the myTextutils website.
10. Deselecting the copied text

Figure 1.8: Selected Copy Text Issue


Whenever we copy the text, it results in selecting the entire
text.
Solution: To overcome this issue, we will edit our
handleCopy function, available in "textform.js".
Add the below code in handleCopy function:

document.getSelection().removeAllRange();

Our issue has been successfully resolved!


Deploying the Application
Create your Build folder by using the npm run Build
command and drag and drop the build folder in Filezilla as
we have done in the previous tutorial, and restart your
nginx. All changes will be reflected in our application.

So, here we complete the 19th article of this React series. In


the upcoming articles, we will be covering some new
concepts of React and will be creating some mind-blowing
projects that would allow you to understand React
completely.

Thank you for being with me throughout the article. In the


next article, we will look at the solutions of exercise 2. Till
then, Keep learning and Keep Coding.

OceanofPDF.com
Exercise 2: Solutions +
Shoutouts | Complete
React Course Article #20
In the last tutorial, we have created our amazing TextUtils
application and have successfully deployed it. In this
tutorial, we will be solving the exercise which was assigned
to you in the 14th tutorial of this React course.

Note: We are just doing the following changes to our


application just to learn something new and hence would
not be deploying it in our mytextutils.com application.
Let’s remove the Enable Dark Mode button instead of that
we would be creating a color palette, which would change
the background color of our application.

Creating A Color Palette for TextUtils


Follow the below steps to create the color palette for the
TextUtils application:
1. Editing Toggle Mode Function
If you remember toggle mode was the function, which was
responsible for switching between dark and light mode and
we have assigned it to our ‘Enable Dark Mode’ Switch. We
need to make some changes to that function so that while
clicking on the desired palette it changes the background of
the application to that specific color.
Toggle Mode Function:
const toggleMode = (cls) => {
console.log(cls)
document.body.classList.add('bg-' + cls)
if (mode === 'light') {
setMode('dark');
document.body.style.backgroundColor = '#042743';
showAlert("Dark mode has been enabled", "success");
}
else {
setMode('light');
document.body.style.backgroundColor = 'white';
showAlert("Light mode has been enabled", "success");
}
}

Explanation: We have assigned a class(‘cls’) parameter in


the toggle mode function. ‘cls’ will be the value that we
want to set our mode as. Suppose, you click on the primary
button having this function, then this function will be
invoked with the ‘cls’ value as primary. This means that the
background color will be ‘blue’ and the ‘primary’ keyword
will be printed in the console, as we have used ‘cls’ with
them.
Creating a Custom palette
We would be creating the custom palettes in the Navbar so
let’s open Navbar.js and add some buttons. We are adding
blue, Yellow, Red, Green buttons as:
Blue palette:
<div className="bg-primary rounded mx-2" onClick=
{props()=>{props.toggleMode('primary')}} style=
{{height:'30px', width:'30px', cursor: 'pointer'}}></div>

Green palette:
<div className="bg-success rounded mx-2" onClick=
{props()=>{props.toggleMode('success')}} style=
{{height:'30px', width:'30px', cursor: 'pointer'}}></div>
Red palette:
<div className="bg-danger rounded mx-2" onClick=
{props()=>{props.toggleMode('danger')}} style=
{{height:'30px', width:'30px', cursor: 'pointer'}}></div>

Yellow palette:
<div className="bg-warning rounded mx-2" onClick=
{props()=>{props.toggleMode('warning')}} style=
{{height:'30px', width:'30px', cursor: 'pointer'}}></div>

Similarly, You can create a palette of your desired Colors.

Explanation: In the above code, We have assigned the


ToggleMode function to the Onclick properties of the
buttons.

For example, On clicking the primary button the Toggle


Mode function will be invoked with the ‘cls’ value as primary.
Remember we have used ‘cls’ in console.log() and also with
background color, so the background color of the application
will turn ‘Blue’, and the ‘primary’ keyword will be printed in
the console.

In a similar fashion, the toggle mode function will be


invoked for other keywords, such as warning, danger,
success, etc, as well.

Result: Now, On clicking the button having a specific color


changes the background of our application to that color.
Figure 1.1: Result

Remove Body Classes


Bug: You might have noticed that you are unable to use the
complete palette without reloading the page. This issue
occurs as once we have entered our class(‘cls’) to the
function, that is we have clicked on any palette, then a new
background class(‘cls’) will be ignored until and unless the
old class is removed.
Solution: To solve this issue we would create a function
removeBodyClasses. This function will remove all the
classes from the document.body. The function is as follows:

const removeBodyClasses = ()=>{


document.body.classList.remove('bg-light')
document.body.classList.remove('bg-dark')
document.body.classList.remove('bg-warning')
document.body.classList.remove('bg-danger')
document.body.classList.remove('bg-success')
}

Now, we would Run this function while toggling mode.


Figure 1.2: Using Remove Body Classes function

Our Application
Here is the demo of our Color Palette. On clicking the Red
palette, the background of our application changes to Red.

Figure 1.3: Our Color Palette


Hence, we have successfully created our color palette.

So here we complete the 20th article of this React series. In


the upcoming articles, we will be covering a lot of new
concepts of React with some new and interesting projects
that would allow you to understand React completely.

Thank you for being with me throughout the article. In the


next article, we will be fixing a few more TextUtils issues. Till
then, Keep learning and Keep Coding.

OceanofPDF.com
ixing few more Textutils
Issues | Complete React
Course Article #21
Earlier, we have finalized our Textutils application. But in the
last video, we have made some changes to our application.
So, In this video, we will revert the changes made in the
20th video and would also fix some issues in our application.
Reverting the changes of the
previous video
We would copy the code from GitHub, till the 19th video,
and would add it to our application to restore its original
form.

Figure 1.1: Copying earlier Code from Github

We are copying the code of "app.js" and "navbar.js" as we


have edited these two files in the last video to create a
palette.
Figure 1.2: Our application

Hence we have successfully restored our application of the


19th video.
Fixing Issues
There are still some issues with our application. So, let’s
open our application in localhost by using the npm run start
command, and begin solving them.
1. Word Counting Error

Figure 1.3: Word Counting Issue


We have typed three words in the textbox but still, the word
count is showing it as one. This issue occurs as we have
forgotten to split the string with a new line. We would like to
split it by space and a new line. To do so, Go to textform.js
where we have written the code for counting words, and
edit it as follows:

<p>{text.split(/\s+/).filter((element)=>{return
element.length!==0}).length} words and {text.length}
characters</p>

Here, We are using the regular expression(regex) instead of


space. The \s is the common shorthand in regex for any
whitespace character, including newlines and ‘+’ denotes
more than one.

Figure 1.4: Fixed Word Counting Issue


Our Word Counting issue has been fixed!
Note: We would remove the unnecessary comments and
Console.log().
2. About page arrow Invisibility
In the dark mode, the side arrows in the accordion
component of our About Page disappear due to their
matching color with the background. We can easily fix this
issue by adding the below CSS code to accordion-
button::after in index.css.
.accordion-button::after {
filter: invert(1);
}

Figure 1.5: Result


We have successfully resolved this issue
3. Home page Highlighted
Our home section in the navbar is always highlighted, even
if we are on the about page. To overcome this issue just
remove the active class from Home.
4. Copy to Clipboard
We are now using the navigator API to copy the text of the
textbox. Hence we could remove the code of the select and
deselect text from our application.
Deploying the Application
Create your build folder by using the command:
npm run build

Drag and drop the build folder in FileZilla as we have done


in the previous tutorial and restart your nginx. All changes
will be reflected in our application.

Congratulations!! We have finally completed our TextUtils


project and have successfully deployed it. From the next
video, we would start creating a new project and would
learn some amazing concepts of React.

Thank you for being with me throughout the article. In the


next article, we will start Project 2 in which we will setup +
get an introduction on Class-based components. Till then,
Keep learning and Keep Coding.

OceanofPDF.com
Project 2 Setup +
Introduction to Class
based components |
Complete React Course
Article #22
Till now, we have created our Textutils application by using
Function-based components, and now we would begin
learning about the Class-based components by creating a
NewsMonkey application. So let’s create our News app and
continue our journey of React.
Create a React App
Open Windows Powershell (shortcut: Shift + Right-click in
folder ) and use npx create-react-Newsapp command to
create a new React app. We have already studied the folder
structure of a React app and also know that "app.js" is the
file that has our app component.
Class-based component
Class components are basically ES7 Classes. A class
Component can also receive props as Input and return
HTML. A class component can also maintain some
information that is private to that component and can use
that information to describe the user interface.
Creating class component:
Now, whenever you create a class component, we need to
include two imports that are the React and the Component
class from React like this:
import React, { Component } from 'react'
After this, you have to just define a class. Remember that
for a class to become a react component. There are two
simple steps. The first step is that it should extend the
component class from React. Secondly, The class has to
implement a render method that will return null or some
HTML. Code:

export default class App extends Component {


render() {
return (
<div></div>
)
}
}

Hence, we have successfully created our class component!

Note: To save our time, Instead of writing such lengthy


code, we can use Snippets. To use a snippet, just install the
ES7 React/Redux/GraphQL/React-Native snippet extension in
your VS Code.
In app.js:
Now to generate the class-based component skeleton, you
can simply use the ‘rcc’ snippet. This feature occurs as we
have installed the above extension. We can render the
content and components in our application by writing some
JSX.
Difference between Function and
Class-based Component:
You might be wondering what the advantage of using one
over the other is and when exactly you should use a
particular component. Below is the image discussing these
points, but you have to keep in mind that you might only
partially understand the discussion, and it is completely fine
at this moment as we are listing down the topics which we
haven’t covered yet.

Figure 1.1: Difference between the two components

These topics will be discussed in detail in the upcoming


articles.

So here we complete the 22nd article of this React series. In


the upcoming articles, we will be creating our NewsApp
application by using the News API and would be learning
some new concepts of React.

Thank you for being with me throughout the article. In the


next article, we will create Component Structure of our
NewsMonkey React App! Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Component Structure of
our NewsMonkey React
App | Complete React
Course Article #23
In the last video, we learned how to set up this project. In
this project, we are going to create a news application
named NewsMonkey. So, without further ado let’s begin:
The component structure of our
application
Structure: We would create a Navbar component at the top
and at the middle of our application, we would add a ‘news’
component that would contain our news items.

Figure 1.1: Structure of News Monkey

Navbar Component:
It will have navigation of different pages of our application,
like About, Home, etc pages.

News Component:

The big red component is the News component. It will


contain a lot of ‘NewsItem’ components.

NewsItem Component:

Many of these items will be specific news. For example


Weather news, Sports News, Politics
news, etc.

News Detail Component:

I would like to point out that later on, we would create a


‘NewsDetail’ Component. This component will show details
of specific news when the reader clicks on a specific
NewsItem. Our navbar will remain intact at the top of the
application.

Figure 1.2: News Detail Component


Benefits: Structuring our app in this way lets us easily
manage our application and also helps in reusing the
components again and again.

Getting Started With NewsMonkey


Let’s Start our development server by using the ‘npm run
start’ and start building our Amazing NewsMonkey
Application:
Note: We will be using Bootstrap to get some design
Components for our application.
Using Bootstrap
Visit getBootstrap.com and copy-paste the starter Template
of Bootstrap in your "Index.html" file. Now, we are ready to
use the components of Bootstrap. Make sure to remember
the below points while copying the code from Bootstrap:
1. Close those tags which don’t have a closing tag
2. Replace the "Class" keyword with "ClassName"
3. Replace href= “#” with href= “/”
Changing Title and meta description
We have added a fancy and SEO-friendly title and meta
description to our NewsMonkey application:
Figure 1.3: Adding title and meta description
Navbar component
Let’s begin creating our application from Navbar. Firstly we
would create a "Navbar.js" file and would add a class-based
component to it. Secondly, we would copy-paste the code of
the Navbar component from Bootstrap. After this, we would
make our desired changes in the Navbar. We have
successfully created our React Component and now we
would like to render it in our application.
Using Navbar component
We know that "App.js" is the file that is being rendered in
our application. So, We have to use this Component in our
"App.js" to render it in our application.

Figure 1.4: Using Navbar component

The Navbar of NewsMonkey has been successfully added.

News Component
We would like to create a ‘news’ component, that would
reside in the center of our application, and it will contain all
the NewsItem components. So let’s create a new file:
News.js:
Create a "news.js" file and add a Class-based component to
it. Now, we would return the desired content which we want
to render in our application. After doing so, we would add
this component to our "App.js".

Figure 1.5: Using News Component


"NewsItem.js"
Create a "NewsItem.js" file and add a Class-based
component to it. Now, we would return the desired content
which we want to render in our application. After doing so,
we would add this component to our "News.js". Hence, Our
News.js file is being rendered in app.js and the News.js file
contains our NewsItem Component.
Figure 1.6: Using NewsItem Component in "news.js"

Hence, the News item component has been successfully


added to our News component.

In the upcoming articles, we will be fetching data in our


application by using a news API and will learn some new
concepts of React.

Thank you for being with me throughout the tutorial. In the


next tutorial we will fetch API Key from News API. Till then,
Keep learning and Keep Coding.

OceanofPDF.com
Fetching API Key from
News API | Complete React
Course Article #24
In the last tutorial, we learned how to set up our News
Monkey App. In this video, we will be fetching the API key
from News API and designing our NewsMonkey application.
So, without further ado, let’s begin:
News API
We would be using a News API to render news in our news
monkey Application. To check out the news API, click here.
After that, log in to the news API by filling up some basic
details like Name, Email, Password, and get your API key.
After you are logged in, you will see your live API key in
every example. We would be using the Top headlines
Endpoint for our application.

Figure 1.1: Using Top headline Endpoint

After doing so, we would get some sample response news


for our application. In order to do that, copy the Definition
Url and search for it on the internet to get the example
response News as shown below:
Figure 1.2: Our Sample Response News

Note: We are getting the output as a parsed JSON because


we have installed ‘JSON view’ extension. We will disable the
extension and will copy the raw JSON code.

Figure 1.3: Copy the Raw JSON code


Using NewsAPI in News Monkey
Create a new file named sampleOutput.json and paste the
sample response code into it. You can use the format
document option to perfectly format your raw JSON code.
Remember, It is just a piece of sample news and not real-
time news. These sample articles will act as our News Item.
As for now, we have four articles.

Figure 1.4: Four News Articles

Enhancing News Item Component


Visit bootstrap to get some designing components for the
NewsMonkey application. We would like to use Cards to
display our NewsItems. So, Copy the code of your desired
card and paste it inside NewsItem.js as shown below:

Figure 1.5: Adding Cards in NewsItem

Now, we will change the Title and Description of every card.


To do that, we will be taking the title and description as a
prop in the NewsItem.

Using props in class-based component


We would be passing the title and description of the News
as a prop.

Figure 1.6: Using Props with class-based Component


Explanation: Above, We have used a destructuring method
of Javascript. It allows us to extract values from arrays and
objects and lets us assign them to other variables. In our
case, this.props is an object, and we are extracting the title
and description from that object.
Hence, we can easily pass the title and description to every
newsItem.

Adding Title and Description


For the demo, We are passing the title as ‘myTitle’ and the
description as ‘mydesc’ in the NewsItem from News.js.

Figure 1.7: Passing Title and Description

Result: We have successfully added the six NewsItems


Components and have passed the Title and Description to
one of our NewsItem Components.
Figure 1.8: Result
Enhancing NewsMonkey
Our application isn’t looking that amazing, so let’s add some
Styles and make it Outstanding. In order to do that, we
would add all these news items in the container and can add
our desired CSS to them. Here, We are providing a grid
layout to our cards.

Figure 1.9: Structuring our NewsItem properly


Result: We have successfully added a heading and have
aligned our three cards in one row. Now our application is
looking adequate. Here’s how it looks:

Figure 1.10: Our Application

Adding Sample Images to card


In the sample response code of news API, we are provided
with a Sample Image URL. We can use this URL in the ‘img
src’ tag of the NewsItems Card.

Figure 1.11: Image Url

In order to use those images in the cards, simply copy the


URL and paste it inside the ‘img src’ tag of the NewsItems.

Result: this is how our News Cards looks like:

We have added these images just for the demo. Later on,
we will be passing this image Url as a Prop.

So here we complete the 24th article of this React series. In


the upcoming articles, we will be enhancing our application
by restructuring the application and adding the images
dynamically. In addition to that, we would also read data
from the API and would be rendering it in our application.

Thank you for being with me throughout the tutorial. See


you all in the next tutorial. Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Understanding state in
class based components |
Complete React Course
Article #25
In the last tutorial, we have seen how we can use props in
class components. In today’s video, we will talk about state,
props, and constructors.
Passing ImageURL as a Prop
First of all, you have to use the Image Url with the props
object. After that, We would pass the image URL in the ‘img
src’ tag. Now, let’s pass content (URL of Image) in this
‘imageURL’ from News.js as shown below:

Figure 1.1: Passing Image as a Prop


Hence, we have successfully passed the image as a prop in
the first News Item.
Using States in Class Components
The first step is to create a state object and initialize it, and
this step is usually done inside the class constructor:
Constructor
If you don’t know, the constructor is a method used to
initialize an object’s state in a class. Remember, within the
constructor, we will call the super method. This is required
because we extend react component class, and a call has to
be made to the base class constructor.
Syntax:

constructor(){
super()
}

Creating the State object


After doing this, we create our state object. For now, let
‘this.state’ equals an empty object.

constructor(){
super()
this.state = {
}
}
Remember, we are using the class-based components, so
don’t forget to use the ‘this’ keyword. By the way, State is
the reserved keyword in react. So, when you declare
this.state, react understands your intention.
Hence, we have successfully created a state object. Now
let’s go ahead and initialize a property.
Create a variable
Here, we will be creating an article variable. We would be
using all the articles of ‘sampleoutput.json’ in this article
variable as an array.
Accessing this array
We can easily access this array from the constructor by
using ‘this.articles’ in the state. We can even add some
more properties in this.state. For example, we are adding a
loading property to our application.

Figure 1.2: Using States in Class Components


Revising Props and State
At this point, If you are confused with the concept of Props
and State in React. Here is a quick comparison between the
two to clear your mind.

Figure 1.3: Quick Review between State and prop

In the next article, we will understand how to iterate this


array and show up all the articles in our NewMonkey
application. Here’s how our application is looking at this
point of time:

Figure 1.4: Our NewsMonkey Application

So here we complete the 25th article of this React series. In


the upcoming article, we will be enhancing our application
and would be understanding a few more concepts of React.

Thank you for being with me throughout the tutorial. In the


next tutorial, we will be Looping through an array in JSX to
display NewsItems from state. Till then, Keep learning and
Keep Coding.

OceanofPDF.com
Looping through an array
in JSX to display
NewsItems from state |
Complete React Course
Article #26
In the previous articles, we have seen how to set states and
props in our News Monkey application. In today’s video, we
will populate the content and desired images in our
application. So without further ado, let’s begin:
Rendering Articles in NewsItems
Earlier, we have passed the articles of sample response in
the components of News.js. We have set the articles array
as a variable and have used it as a state. Now, We want to
iterate the articles array present inside the state, and then
we would render these articles in our NewsItem Component.
Iterating the Array
At this point, the title of all NewsItem Components is
‘mytitle’ We have to change it with the title of the News
Element. In a similar way, we want to change the
description and Image of the NewsItems.
Figure 1.1: Passed Values in Title, Description, and Image
URL

The title, description, and URL to an image of an article are


already provided in the sample response as shown below:

Figure 1.2: Provided Title, Description, and URL to an


image

We want to change the values of Title, Description, and


Image URL from the previously passed values(Figure 1.1) to
the values provided in the sample response of the article.
Getting Started
To do that, first of all, we have to iterate the articles array
and then render its data in the NewsItem. We can do so by
using the map() method.
map() method: The map() method is the most commonly
used function to iterate over an array of data in JSX. You can
attach the map() method to the array and use a callback
function that gets called for each iteration.

Figure 1.3: Returning the NewsItem Component

Explanation: In our case, The map would go through each of


the objects in the array, and it will make each individual
array item available to us as an element. Notice, Inside the
arrow function, we have returned the NewsItem Component.

Result: The four News Items Components get added to the


News Monkey Application. We haven’t passed the values
yet, so all of the components are having the same Image,
Title, and description as shown below:
Figure 1.4: Result
Passing Title, Description, and URL to
Image
Now, let’s begin passing the provided values of articles in
our NewsItem Components. We would be passing the title,
description, and URL to the image in the respective props of
the NewsItem Components.

Figure 1.5: Passing Title, Description, and URL to Image

Result: Hence, we have passed the provided values of title,


description, and image to our four NewsItem Components.
Here’s how our NewsMonkey application looks like:
Figure 1.6: Our application after passing the values

Making the 'ReadMore' button


Functional
We would like to display the complete News in a New Tab
whenever the user clicks on the ‘ReadMore’ button. To do
so, we would add a newsUrl. We would be passing the value
of the URL of the respective article to newsUrl.
Figure 1.7: Using NewsUrl as a Prop

Above, we have used NewsUrl as a prop and have even


assigned the link of ‘Read More’, which is the functionality
to open it in a New Tab. Here, the ‘a href’ is equal to the
news Url. We would be passing the URL of the respective
article in it from News.js as shown below:

Figure 1.8: Passing the Url in the prop

Enhancing the Structure


The length of all the NewsItems Cards isn’t equal due to
this, our NewsMonkey application is looking destructured.
Therefore, To fix this issue, we would limit the length of
visible characters in the title and description of the
NewsItems Cards. This can be accomplished by using the
slice method of Javascript as shown below:

Figure 1.9: Using slice() Method


Our Application
Here’s how our application looks like after so much
enhancements:
Figure 1.10: News Monkey Application

So here we complete the 26th article of this React series. In


the upcomingarticles, we will be enhancing our application
and will be using the fetch API to make HTTP calls, due to
which we will be rendering the latest news dynamically in
our News Monkey application.
.
Thank you for being with me throughout the tutorial. In the
next tutorial, we will Use Fetch API to populate NewsItems.
Till then, Keep learning and Keep Coding.

OceanofPDF.com
Using Fetch API in React
to populate NewsItems |
Complete React Course
Article #27
In this article, we will be rendering the news from NewsAPI
in the NewsMonkey application. So let’s Populate our
NewsItems using the NewsAPI:
News API
First of all, you have to visit the News API website. You will
get a lot of the latest news categories, which you can use in
your application. We would like to render the ‘Top headlines
in India’ in our NewsItems. For that, we will copy the URL of
‘top business headlines in the USA’ and will use the filter to
remove the business category and select the country as
India.
Removing the article variable and
State
Till now, we have created an article variable and have used
it in our state. Now, we would remove those articles and the
created state, as we don’t require them anymore. As of now,
we will render the data in our application from the
endpoints. For that purpose, we will change the articles with
the help of the componentDidMound method.
componentDidMount() method
This method gets invoked once the component has been
rendered.
As a result, the constructor of our application gets executed
first, followed by the ‘render method,’ and at last, the
ComponentDidMount() method is invoked.
Note: ComponentDidMount() is a lifecycle method. We will
be discussing the lifecycle methods in detail in the
upcoming videos.
Fetch data in React using the
async/await syntax
First of all, we would use our copied News URL in the
component Did Mount method as a variable. This URL will
help in fetching the News in our application.

Code:

componentDidMount(){
console.log("cdm");
let url = "https://newsapi.org/v2/top-headlines?
country=in&apikey=dbe57b028aeb41e285a226a94865f7a7
";
}
After that, we would be using the Fetch API. Remember, the
fetch API takes a URL and returns a promise. Here, how you
can use the fetch API:-
Code:

componentDidMount(){
console.log("cdm");
let url = "https://newsapi.org/v2/top-headlines?
country=in&apikey=dbe57b028aeb41e285a226a94865f7a7
";
let data = fetch(url);
}
Using Async and Await
Async keyword is used to make a function asynchronous.
Async can wait inside its body to resolve for some of the
promises. The await keyword will stop the execution until a
defined task is completed. In our case, it will wait for the
promise to be resolved.

Code:

async componentDidMount(){
console.log("cdm");
let url = "https://newsapi.org/v2/top-headlines?
country=in&apikey=dbe57b028aeb41e285a226a94865f7a7
";
let data = await fetch(url);
console.log(parsedData);
}

Once, The promise is resolved, it would provide us the data.


We can parse the data as text or JSON. After that, we would
use the setState method to set the state of the articles as
parsed Data articles.
Code:

async componentDidMount(){
console.log("cdm");
let url = "https://newsapi.org/v2/top-headlines?
country=in&apikey=dbe57b028aeb41e285a226a94865f7a7
";
let data = await fetch(url);
let parsedData = await data.json()
console.log(parsedData);
this.setState({ articles: parsedData.articles })
}
Resolving “Cannot Read property
‘slice’ of null” Error
This Error occurs as some of the values, such as title,
description, are null for some of the articles. Due to this, we
can’t use the slice() method to set the limit of the
characters. To resolve this issue, we would be using the
ternary operators as follow:

<div className="row">
{this.state.articles.map((element)=>{
return <div className="col-md-4" key={element.url}>
<NewsItem title={element.title?element.title.slice(0,
45):""}
description={element.description?
element.description.slice(0, 88):""} imageUrl=
{element.urlToImage}
newsUrl={element.url} />
</div>
})}
</div>

Explanation: Now, If in case the element title or


description is Null, then a blank space will be rendered, that
is the else statement. Otherwise, the sliced content will be
rendered in our NewsItems.

Our Application: All the latest articles get populated in our


News Monkey Application.
Figure 1.1: NewsMonkey Application

Resolving the ‘Image Not Rendering’


Issue
Our application is quite astounding, but for some of the
NewsItem Components, the image isn’t rendering in the
NewsItem. Let’s fix this issue and wrap up this tutorial:
Figure 1.2: Image Not Rendering in the NewsItem

Here, the image is null for one of the Articles. Due to this
reason, the image isn’t rendering in Our NewsItem. To
resolve this issue, we would use a default Image URL when
the ‘Url to the image of article’ is Null. For that, we would
use the ternary operators in the ‘imgsrc’ tag of NewsItem.js
in the following way:

Code:
<img src=
{!imageUrl?"https://fdn.gsmarena.com/imgroot/news/21/08/
xiaomi-smart-home-india-
announcements/-476x249w4/gsmarena_00.jpg":imageUrl}
className="card-img-top" alt="..."/>

Hence, the ‘image not rendering in the News Component'


issue has been successfully resolved.
Here we complete the 27th article of this React series. In the
upcoming articles, we would be learning a lot of new
concepts of React by enhancing our NewsMonkey
application.

Thank you for being with me throughout the tutorial. In the


next tutorial, we will be Adding Previous & Next Buttons to
populate NewsItems. Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Adding Previous & Next
Buttons to populate
NewsItems | Complete
React Course Article #28
In the last article, we have seen how to update all the News
Articles with the help of ComponentDidMount, and also we
have learned how we can fetch data from the API in our
application. But, we are facing an issue in our application,
that is all the articles are not getting displayed in the
application. Let’s fix this issue by adding one more page to
display the remaining articles:
Creating Page Parameter State
We have found that only some of the articles are being
rendered in the News Monkey application. The other articles
are rendered on the Next Page. We would be fetching the
remaining articles on the Next Page of the NewsMonkey
application. For that, we would firstly add a page parameter
to the state as follow:

constructor(){
super();
this.state = {
articles: [],
loading: false,
page: 1
}
}

Creating Previous and Next Buttons


Below, We have added the buttons and have edited them in
our desired way. Here, we have added an arrow to the
buttons and have even aligned the buttons perfectly.

Figure 1.1: Adding Buttons and Editing them


The 'previous' and 'next' buttons will be added to our
application.
Adding the Onclick Function to the
Buttons
Now, we want to render the next set of News by clicking the
Next Button and the previous news by navigating through
the previous button. For that reason, we would assign an
OnClick function to the buttons. We are adding the
‘handleNextClick’ function to the Next button and the
‘handlePrevClick’ to the previous button.

Code:

<div className="container d-flex justify-content-


between">
<button type="button" class="btn btn-dark" onClick=
{handlePrevClick}> &larr; Previous</button>
<button type="button" class="btn btn-dark" onClick=
{handleNextClick}>Next &rarr;</button>
</div>
Copy

Disabling Next And Previous button


at a certain instance
Moreover, we would like to disable the previous button when
the page number is equal to or less than one, that is when
the first page is getting rendered in the application.
Code:

<div className="container d-flex justify-content-


between">
<button disabled={this.state.page<=1} type="button"
class="btn btn-dark" onClick={handlePrevClick}> &larr;
Previous</button>
<button type="button" class="btn btn-dark" onClick=
{handleNextClick}>Next &rarr;</button>
</div>

Similarly, we would also disable the Next Buttons when all


the articles have been rendered. Thus, we would use the
page size parameter. This parameter only renders the
specific articles on a single page. For example, if the page
size parameter is equal to ‘two’ then only ‘2’, of all the
articles, will be rendered in the application.
Math.ceil() method
We have a total of 38 results so if we render 20 News on one
page then it will take 1.9 pages to render all the NewsItems.
But, we want to display two pages. Thus, To overcome this
issue we would use math.ceil() method. This method rounds
a number up to the next largest integer.
Using if-else Statement
Now, we would like to perform the below functions only
when the next page exists. Otherwise, we would disable the
button, that is no function will be invoked. To do so we
would use the if and else statement in our handleNextClick
function.
Creating 'handleNextClick' and
'handlePrevClick' Function
We would update the page state and content of
ComponentDidMount by using these functions. That is, We
would like to increase the page number by ‘1’ on clicking
the Next button and on clicking the previous button we
would decrease it by 1. To do so use the following code:
For the next button:
handleNextClick = async () => {
console.log("Next");
if (this.state.page + 1 > Math.ceil(this.state.totalResults /
20)) {
}
else {
let url = `https://newsapi.org/v2/top-headlines?
country=in&apikey=dbe57b028aeb41e285a226a94865f7a7
&page=${this.state.page + 1}&pageSize=20`;
let data = await fetch(url);
let parsedData = await data.json()
console.log(parsedData);
this.setState({
page: this.state.page + 1,
articles: parsedData.articles
})
})
}

Explanation: In the above code we have used the if-else


statement to use the function only if the next page exists
otherwise it won’t be executed. Now if the function is
executed then the state of the page will be updated by 1.
For the previous button:
handlePrevClick = async () => {
console.log("Previous");
let url = `https://newsapi.org/v2/top-headlines?
country=in&apikey=dbe57b028aeb41e285a226a94865f7a7
”&page=${this.state.page - 1}&pageSize=20`;
let data = await fetch(url);
let parsedData = await data.json()
console.log(parsedData);
this.setState({
page: this.state.page - 1,
articles: parsedData.articles
})
})

Result: Now, on clicking the Next Button we can move to


page ‘2’ where the remaining articles are being rendered.

So here we complete the 28th article of this React series. In


the upcoming articles, we will be enhancing our application
and would be learning a lot more amazing concepts of
React.

Thank you for being with me throughout the tutorial. In the


next tutorial, we will be Adding the load spinner & variable
pageSize to NewsMonkey. Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Adding loading spinner &
variable pageSize to
NewsMonkey | Complete
React Course Article #29
In the last article, we have enhanced the NewsMonkey
Application by rendering the News from the server with the
help of Fetch API. In this tutorial, we will fix some issues with
our news app and also we would add some more features to
the NewsMonkey application. So, without further ado let’s
begin:
Using Props
Now, we would be sending all the required data in the form
of props. In our News Component, We can pass many pieces
of information as props, that is we would be using them as a
variable. For example, We would like to display the number
of news items on a single page of the News Monkey
Application.
Page Size as variable
In our case, we would like to set page size as a variable. At
this moment, the page size is set as 20, which means 20
articles are being rendered on each page of the application.
Suppose, we would like to render only 5 articles in the
NewsMonkey application. But this time we would be setting
the page size as a variable.
To do so follow the below steps:
1. In app.js:
Firstly, we would be passing props in the variables of news
Component from the app.js as shown below:
<News pageSize={5}/>
2. In News.js:
After that, we would be using the page size as a variable
and would be accessing the props by using
"this.props.pageSize" as shown below:

Figure 1.1: Page Size as a variable

Remember to replace "20" with "this.props.pageSize" as


previously we have set the page size as 20 and now we
would like to replace it with "this.props.pageSize", which is
5.
Result: Hence, only five news items are being displayed in
the NewsMonkey application.
Figure 1.2: Five NewsItems on a Single Page
Adding Loading Spinner
Firstly, we would download a spinner from the internet. We
are using the ajaxload website, You are free to use any of
the spinner generating websites. After that, Copy the
downloaded file and paste it inside the src of the NewsApp.

Create Spinner component


We have created a separate file for the spinner named
"spinner.js". Generate a class-based component in it and
import the downloaded spinner file in it. In our case, it is
"loading.gif" so we have imported it. We have used the
imported spinner in the img src.

Figure 1.3: Creating Spinner Component

Hence we have successfully created the Spinner component

Using Spinner component


Since we would like to show the spinner while loading. Thus,
we will change the loading from false to true. Now, we want
to show the spinner when the loading is true otherwise not.
To do so we would add a simple javascript logic in our
application as follows:
{this.state.loading && <spinner/>}

Explanation: The above logic means if the state of loading is


true then only display the spinner in the application
otherwise not.
Using Spinner while clicking Next and Previous
buttons
Now, we want the Loading to become true whenever the Url
is being hit, that is a request is being made to the server.
For now, we are adding the loading in our handlePrevClick
function as well as the handleNextClick function.
Figure 1.4: Using Spinner Component

Note: You can also add the Loading at any instance, like
while switching the pages or rendering the application.

Result: Now, the loading is shown while making a request.


But, the content and loading are showing up at the same
time.

Figure 1.5:Result and the Issue

Fixing Issue
Thus, To fix this issue we would like to do one more thing to
the application, which is erasing the NewsItems when the
loading is going on. To do so, we would go to news.js and
would edit the code in the following way:
Figure 1.6: Fixing Issue

Explanation: If this.state.loading is true then don’t show


any NewsItem otherwise render the news items.

The NewsMonkey Application


Here’s how our application looks like at this instance:

Figure 1.7: NewsMonkey Application

Here we complete the 29th article of this React series. In the


upcoming articles, we would be creating different categories
of the News and would be passing some more props to the
NewMonkey Application.
Thank you for being with me throughout the tutorial. In the
next tutorial, we will be Adding Categories & propTypes to
NewsMonkey React App. Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Adding Categories &
propTypes to NewsMonkey
React App | Complete
React Course Article #30
In the last article, we have enhanced our NewsMonkey
Application by adding a loading spinner. In today’s tutorial,
we would pass categories, such as Sports, General,
Entertainment, Business, etc in the navbar of the
application. So without further ado let’s begin:
Passing "country" as a Prop
Earlier, we have passed India as a country to the filters of
the NewsItems. Now, since we are going to change the
country for other different NewsCategories so we would be
passing ‘country’ as a Prop. To do so follow the below steps:
1. Firstly, You need to pass the country as a prop from App.js
as shown below. For the demo, we are passing the country
like India:
<News pageSize={5} country= "in" />

2. Secondly, we would be using the created country prop in


URL to filter the News as shown below:
let url = `https://newsapi.org/v2/top-headlines?
country=${this.props.country}&apiKey=dbe57b028aeb41e
285a226a94865f7a7&page=${this.state.page +
1}&pagesize=${this.props.pageSize}`;

Prop types in Class-Based Component


React has a mechanism for props authentication called prop
types. As some functions need compulsory arguments,
similarly in react components might require a prop to be
defined. Otherwise, it won’t render properly.
Using PropTypes with static variable
Since we are about to use prop types in our application so
firstly we have to import them into the "News.js" as follows:
import PropTypes from 'prop-types'
\

Static variable
The static variable can be used to refer to the common
property of all objects. Static is the property that belongs to
the class only. Earlier in React, we used to define props
outside of the class. But now we will be defining them inside
the class by using the static variable.
Creating Static Variable
Now, we would create a static variable inside the class to
write proptype. Remember, we would be using static default
props as well.

Figure 1.1: Using Prop Types with Static variable


Till now, we have created two props, which are ‘country’ and
‘Page size’. Here, we have passed the default value to the
props also we have declared the prop type as string and
number respectively for the two values. Later on, we would
be adding more proptype in this static variable.

Creating Categories
Moreover, we would like to show the different categories in
the Navbar such as Business, Entertainment, General,
Health, Science, Sports, and technology. To display these
categories in the Navbar, You will have to add all the above
categories in the Navbar.js as list items.

Figure 1.2: Adding Categories in Navbar.js

Result: We have successfully added all the categories in the


Navbar. At this moment all the href links are /about so
clicking on any of the categories will still render the same
news.
Note: We would be adding the proper link to these
categories later on.
Passing Categories as Props
Till now, we have created the different categories, but now
we would like to pass the category from App.js. For the
demo, we are passing the category as science in the
following manner:

<News pageSize={5} country= "in" category="science" />

Secondly, we have to embed this category in the URL. To do


so we have to first add the category in the static default
prop and static prop type variable.

Figure 1.3: Set Prop Type of Category

Now, We can easily pass the Category to the URL of


ComponentDidMount, handlePrevClick, and handleNextClick
function as follows:
let url = `https://newsapi.org/v2/top-headlines?
country=${this.props.country}&category=${this.props.cate
gory}&apiKey=dbe57b028aeb41e285a226a94865f7a7&pag
e=${this.state.page +
1}&pagesize=${this.props.pageSize}`;
Result: Here, we have passed the category as ‘science’ and
as a result, we are getting all the NewsItems related to
Science.

Figure 1.4: NewsMonkey Application

So here we complete the 30th article of this React series. In


the upcoming articles, we will be enhancing our
NewsMonkey application by setting up React Router. In
addition to that, we would be fetching all the news items
category-wise.

Thank you for being with me throughout the tutorial. In the


next tutorial, we will be Fetching News category-wise in
NewsMonkey React App. Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Fetching News category
wise in NewsMonkey React
App | Complete React
Course Article #31
In the last article, we have passed the categories and
Proptypes in the NewsMonkey application. In today’s video,
we would be setting up a react-router and would be fetching
the News category wise in our NewsMonkey application.
Install React Router package
Let’s see how to set up react-router in our code:
Procedure: The first thing we have to do is install the react-
router package because it is not a part of the core react
library.
npm install react-router-dom

Set Up routing for our application


Procedure: After installing the package, The first thing you
have to do is go to the root component, that is, your "app.js"
file, and import a few things from the react-router package.
We are going to import the Browser Router as Router,
Switch, Route, and Link from react-router-dom. To import the
following using the below command:
import {BrowserRouter as Router, Switch, Route, Link} from
"react-router-dom"

In App.js
1. Using Router: We have to surround our entire
application with the router component and it means
that we can use the router in the entire application. As
a result, all components that are nested inside this app
component(app.js) get access to the router. Hence, To
surround your app with the router component, use
<Router></Router>

2. Using Switch: The next step is to decide where we


want our page content to go when we go to different
pages. Since we want to access the different News
items with Update Props. So, we are going to use the
switch component (<switch></switch>). The switch
component makes sure that only one route shows at
any one time. All of our routes go inside this switch
component.

3. Using Route: Alright, we need to set up our individual


routes for the pages of different Categories. So, we will
create a route for each page, for which we will be using
the route component(<route></route>). At this
moment, we have General, Business, Entertainment,
Health, Science, Sports, Technology pages of our
application, and hence we are going to place the same
number of routes inside this switch component.

Figure 1.1: Using React Router in NewsMonkey


Remember, that we are using the <Route Exact path= “/”
/> for the exact matching of the endpoint.

Point to be noted: React won’t render the NewsComponent


again while navigating through different categories as it will
render the NewsComponent for the first request. But we
want to rebound the News component with the Updated
Props. To fix this issue we would add a unique key prop to
every route as shown below:

Figure 1.2: Using Key prop to Rebound NewsComponent


result: We would be displaying the News of a specific
Category while the selected path is used as an endpoint in
the URL.

Note: Since we have already learned about react-router so


we won’t be discussing the React router in detail.
In Navbar.js:
We would like to show the specific news when the user
selects the desired category. For example, when the user
visits the sports category then we want to display the news
articles related to sports, to do this we have to refactor the
navbar component. We would replace the "/about" endpoint
with different endpoints related to those specific news
categories, as shown below:

Figure 1.3: Changing the Endpoints of the Categories

Fixing the Reloading issue


You might have noticed that the page is reloading while
switching between different categories so to solve this we
would replace the "a href" keyword with ‘link to’ in
"Navbar.js". To do so firstly, Make sure to import the link
from react-router-dom.

Figure 1.4: Using 'Link to' instead of 'a href'


Result: Now, we can switch between the News of different
categories without reloading the page. Here’s a look at the
NewsMonkey application.

Figure 1.5: The NewsMonkey Application

Here, we complete the 31st article of this React series. In


the upcoming articles, we will be enhancing the
NewsMonkey application by adding time, author, and News
Source details to the React App.

Thank you for being with me throughout the tutorial. In the


next tutorial, we will be Adding time, author, and news
source to News React App. Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Adding time, author and
news source to News
React App | Complete
React Course Article #32
In the last article, we have set up React Router and have
fetched News in the application according to their
categories. In this tutorial, we will be adding the Date and
Time, Author, News Source, and many other fields of the
sample response in the News Monkey Application. So
without further ado let’s begin:
Adding Published Date and Time of
the News
In the sample "output.json", we have been provided with the
PublishedAt field, which we will be adding to our NewsItem.
We are adding the Date and Time field in the News Item
Card as:
<p className="card-text"><small class="text-muted">By
{author} on {date}</small></p>

We would be passing values in the author and date variable.


With the help of the destructuring method of javascript, we
would be getting the author and date from "this.props" as
shown below:
let {title, description, imageUrl, newsUrl, author, date} =
this.props;

In News.js:
Now, we had to pass the "Author" and "Date" from the
"News.js" to the NewsItem component. Then only, with the
help of destructuring, we would be getting the date and
Author information from the props. Here’s how we are going
to do it:

Figure 1.1: Passing the values from News.js

Result: Hence, the published date and author of the article


are shown in the NewsItem component.

Figure 1.2: Adding Author and Date to the NewsItems


Author Field Null Issue
We have noticed that for some of the NewsItems the author
field isn’t being displayed in the NewsItem component. This
issue occurs as the Author field is null for that NewsItem. To
fix this issue we would add a Javascript logic, such that
whenever the author field is null then ‘Unknown’ is
displayed in the author field of NewsItems.
<p className="card-text"><small class="text-muted">By
{!author?"Unknown": author} on {date}</small></p>

Result: Hence, whenever the author will be null for any


NewsItem then ‘unknown’ is displayed in the author field.
Formatting Date and Time
Now, we would like to change the format of date and time
from the ISO time format to the GMT Date time format.

ISO time format: yyyy-MM-dd'T'HH:mm:ss

GMT time format: Fri, 27 Aug 2021 07:00:00 GMT

We can simply do so by creating a new Date object and then


simply convert it into the GMT string as shown below:
<p className="card-text"><small class="text-muted">By
{!author?"Unknown": author} on {new Date
(date).toGMTString}</small></p>

Result: Thus, We have successfully formatted the Date and


Time and have also fixed the ‘null field of Author’ issue in
the application.
Figure 1.3: Formatting Date and Time

Adding Source Badge to NewsItems


We are using the badges from the bootstrap to embed in the
News Monkey Application. Here is the code of our desired
badge which we are adding to the card class of the
NewsItem component. We have edited the badge by adding
the "zIndex" and have also provided the proper alignment
with respect to other NewsItems.
<h5 className="card-title">{title} <span
className="position-absolute top-0 translate-middle badge
rounded-pill bg-danger" style={{left: '90%', zIndex: '1'}}>
99+ </span>

As a result, the above badge will be embedded in the top


right corner of every NewsItem. Now, remember to get the
"source" from "this.props" with the destructuring method of
Javascript. Moreover, we would be passing the Source
information of the respective News in the badge as shown
below:
<h5 className="card-title">{title} <span
className="position-absolute top-0 start-100 translate-
middle badge rounded-pill bg-danger"> {source} </span>

Now, we can simply pass the source in the badge from the
News.js as:
source={element.source.name}/>

Result: Hence, we have successfully added a source badge


to the NewsItems.

Figure 1.4: Added the Source Badge to the NewsItems

Here, we complete the 32nd article of this React series. In


the next articles, we will be enhancing the NewsMonkey
Application by refactoring the NewsComponent to use the
same function in the NewsMonkey React Application.

Thank you for being with me throughout the tutorial. In the


next tutorial, we will learn about Refactoring News
component to use the same function. Till then, Keep
learning and Keep Coding.
OceanofPDF.com

You might also like