Master ReactJS Part 2 MFurqan Riaz
Master ReactJS Part 2 MFurqan Riaz
Legal Notice:
Disclaimer Notice:
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
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:
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:
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
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
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.
let myStyle = {
color: props.mode === 'dark'?'white':'#042743',
backgroundColor: props.mode ==='dark'?'rgb(36 74
104)':'white'
}
In textform.js:
2. Certbot Nginx
apt-get install python3-certbot-nginx
document.getSelection().removeAllRange();
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.
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>
Our Application
Here is the demo of our Color Palette. On clicking the Red
palette, the background of our application changes to Red.
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.
<p>{text.split(/\s+/).filter((element)=>{return
element.length!==0}).length} words and {text.length}
characters</p>
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:
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.
Navbar Component:
It will have navigation of different pages of our application,
like About, Home, etc pages.
News Component:
NewsItem Component:
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".
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.
We have added these images just for the demo. Later on,
we will be passing this image Url as a Prop.
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:
constructor(){
super()
}
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.
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
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);
}
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>
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="..."/>
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
}
}
Code:
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:
Note: You can also add the Loading at any instance, like
while switching the pages or rendering the application.
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
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" />
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.
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.
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
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>
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>
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:
Now, we can simply pass the source in the badge from the
News.js as:
source={element.source.name}/>