Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
French
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranî)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
Welcome to the React full course. In
this course, we'll learn how to build
complex websites with React. And by the
end of this course, we'll build two
projects, a chatbot and an e-commerce
project.
We'll start from the very basics of
React like how to set up React with
JavaScript and we'll learn each feature
in detail step by step. We'll learn the
major features of React as well as
advanced features like how to use React
with a backend, deploy React to the
internet with AWS,
React with TypeScript, and React with
AI.
You can find the sections of this course
below the video here and here.
You can also change the speed of the
video here.
And you can find subtitles for different
languages here.
And after each lesson, I'll give you a
bunch of exercises that you can do on
your own to practice the skills that we
learned. In total, this course has over
125 exercises.
So, with that being said, let's get
started.
I'm going to be doing this course on
Windows, but the steps are the same if
you're using a Mac. Before we begin,
we're going to need two pieces of
software. Number one is a web browser,
and number two is a code editor. The
most popular web browser for web
development is Google Chrome and the
most popular code editor for web
development is VS Code. So I recommend
using these. If you need to install
these, you can search for them on
Google.
Click the link and follow the
instructions to download and install.
Now you'll also need to know the basics
of JavaScript.
React is built on JavaScript and we're
going to be writing a lot of JavaScript
when using React. Don't worry, you don't
need to be an expert in JavaScript. You
just need to know some basic features
like the ones listed here. And I'll also
try to review JavaScript features as we
go through this course. If you want to
learn JavaScript in more detail, you can
check out my JavaScript full course in
the video description.
Finally, you'll need to know the basics
of HTML.
When using React, we're going to be
writing a lot of HTML.
Again, don't worry. You don't need to be
an expert in HTML. You just need to know
some basic features like the ones listed
here. And I'll try my best to review
HTML features as we go through this
course.
If you want to learn HTML in more
detail, you can check out my HTML and
CSS full course in the video
description.
If you have any issues in this course,
you can check the troubleshooting guide
in the description.
Now that we have all the requirements
that we need, we're ready to learn
React.
On our computer, we're going to go to
our desktop and we're going to create a
new folder. So here I'm going to
rightclick and create a new folder.
And this folder is going to contain all
the code that we write in this course.
So let's name it react dashc course and
press enter.
Next we're going to open this folder in
our code editor VS Code. So, we'll open
VS Code
and then click File,
Open Folder
and select the folder we just created.
So, I created my folder on the desktop
and it's this folder right here. So,
we'll select this folder and then click
select folder
and we can close this welcome page.
So, now let's create a new file to learn
React. So up here, we're going to create
a new file and we're going to name it
react-basics.html
and press enter.
As a review, a file that ends inh
contains HTML code and this creates a
website.
Next, we're going to create a website
and we're going to set up React on this
website. Now, to save time, we're
actually going to download some starting
code.
So, we're going to open our web browser,
Google Chrome.
And at the top, we're going to type
super simple.dev/react-basics
[Music]
and press enter.
So, this page has some starting HTML
code we can use to learn React. So now
let's click on this page and we're going
to select all this code by pressing
control A on Windows or command A on Mac
and we're going to copy paste this code
into our file. So we'll right click
copy. We can also press control C on
Windows or command C on Mac
and then open our code editor and then
inside this HTML file we're going to
rightclick and paste. We can also press
control +VV on Windows or commandV on
Mac.
And finally let's save this file by
pressing control S on Windows or command
S on Mac.
Next, we're going to open this file in
our web browser to see what the website
looks like. To make this easier, we're
going to use a VS Code extension called
Live Server. So, the benefit of live
server is it will automatically refresh
the web page whenever we change some
code. So, it's going to make our coding
easier.
If you don't have live server installed,
you can click the extension section and
then search for live server at the top
and then click install.
Once liveer is installed, we're going to
go back to our code and we're going to
open this file in live server by
rightclicking in the file and click open
with live server.
So live server will open the HTML file
using our browser and it's going to
create a website and we should see the
message welcome to super simple dev
react course on this website.
So this message is displayed by React
and this means that we successfully set
up React on this website.
Now, let's go back to VS Code.
And this is the minimum amount of code
that we need to set up React. We're
going to go through this code step by
step to make sure that you understand
everything here.
First of all, what is React? React is an
external library that helps us create
websites easier. Now, there are two
parts to this statement. Number one,
React is an external library. And number
two, React helps us create websites
easier. Let's go through these one by
one. So number one, React is an external
library. First, let's review what an
external library is. So here we have a
bunch of HTML code. An HTML code creates
a website. And now, how do we load
JavaScript onto our website? There are
several ways to load JavaScript on a
website. One way is to use an HTML
element called a script element.
For example, under this div element,
let's create a script element using less
than script greater than and less
than/cript greater than. But our code
editor might autocomplete this for us.
Now, inside this script element, we can
write some JavaScript code. For example,
console.log
the string hello.
As a review, this code displays the text
hello in the console. So now let's save
and we're going to open the console in
our browser. So we'll open Google Chrome
and Liveer is going to automatically
refresh the page and run that JavaScript
code. And now we're going to check the
console by right-clicking and then click
inspect
and open the console tab.
And you'll see that inside the console
we displayed the text hello. And that's
exactly what this code does. So we
successfully loaded this code onto our
website.
We'll go back to VS Code. So this is one
way to run JavaScript code on a website.
First, we create a script element and
then we put our JavaScript code inside.
Another way to run JavaScript is to save
our JavaScript code in a file. So on the
left, let's create a new file
and we'll name it React-basics.js
and press enter.
So when we end a file with js, this file
contains JavaScript code. So now let's
move that code into this file. So we'll
go to our HTML file. We're going to
select this code and then rightclick
cut. We can also press controlX on
Windows or command X on Mac.
And inside our JavaScript file, we're
going to rightclick and paste
and save this file.
Now to run the code inside this file,
we're going to go back to our HTML
and we're going to add an HTML attribute
to this script element. So after this
script, we're going to type space and
then type src equals double quotes. So
the src attribute lets us load
JavaScript from a file.
Inside these double quotes, we're going
to tell the computer which JavaScript
file to load. So we'll type
react-basics.js.
So this will look for a file called
react-basics.js
beside the current HTML file. So it's
going to find the file here, and it's
going to run all the code inside this
file. So now let's save
and open our browser and check the
result.
Live server will automatically refresh
the page. And inside the console you can
see that we display the message hello.
So we're successfully loading code from
inside a file.
We'll go back to VS Code.
And this is a second way to load
JavaScript. We save our JavaScript in a
file and then we load it from the file.
Next, the script element can actually
load code from anywhere on the internet,
not just on our computer. For example,
we're going to open Google Chrome. And
then we're going to create a new tab.
And at the top we're going to type
unpkg.com/sups
simpledev/external
dash library.js
and press enter.
So on this website we have some
JavaScript code. So this is just normal
JavaScript code. it displays a message.
This is an external library inside the
console. So using the script element, we
can actually take this code from this
website and run it on our own website.
To do that, we're going to open VS Code
and inside the src attribute, instead of
loading the JavaScript code from a file,
we're going to load the JavaScript code
from a website. So, first we need the
URL of the website. So, we'll go back to
Google Chrome and at the top this is a
URL and we're going to copy
and VS Code we're going to remove this
file and we're going to paste the URL.
And now let's save.
So now let's go back to our website and
we're going to go to the tab for our
website.
And we're going to check the console.
And inside the console, you can see we
displayed the message, this is an
external library.
So we successfully loaded JavaScript
code from another website.
Let's go back to VS Code.
So using the script element, we can load
JavaScript code from anywhere on the
internet. So this code is called an
external library. An external library is
just code that is outside of our
computer. It's code that someone else
wrote and we can load that code into our
website using the script element.
Now, React is an external library. So,
React is just a bunch of code that is
outside our computer that someone else
wrote and we can load this code on our
website and use it.
So inside our starting file at the
bottom here, these two script elements
load the React external library. So
loads React.js
and React-dom.js.
So let's open these URLs in our browser
and take a look. So we're going to
select this URL and we're going to copy.
And inside Google Chrome, we're going to
create a new tab. And at the top, we're
going to paste the URL and press enter.
And on this website, you can see that we
have a bunch of JavaScript code. So,
this is the code for React. We're just
taking all of this code and then loading
it onto our website.
Let's go back to VS Code. And the same
thing applies to this second URL. If we
select it and then copy
and in our browser create a new tab and
then at the top paste
and press enter.
You can see that this website also has a
bunch of JavaScript code
and this is also the code for React. So,
as you can see, React is an external
library. It's just a bunch of code that
is outside of our computer that someone
else wrote. And we can load this code on
our website and use it.
Now, before we move on, there's two
things you might be wondering about.
Number one, why are we loading React
from Super Simple Dev instead of some
official React URL? So, this just lets
me control the version of React. If we
loaded React from the official URL, you
might get a different version of React
than the one I'm using in this video,
which might cause issues. So, for the
video, we're going to use a super simple
dev URL to make sure that we have the
same version of React and you're able to
follow along.
The second thing you might be wondering
is why are there two external libraries
for React React and React DOM. So React
is designed to be used in different
places like websites and also mobile
apps. So the creators of React decided
to divide it into two external
libraries. React which contains all the
shared features that are used in both
websites and mobile apps and React DOM
which contain features that are specific
to websites. So if we're using React to
create websites, we need to load the
React external library and the React DOM
external library. If we were using React
to create mobile apps, we would load the
React external library and a different
library called React Native.
In this course, we're going to use React
to create websites. So, we're going to
load React and React DOM.
Okay, so we learned that React is an
external library. It's just a bunch of
code that is outside of our computer and
we're going to load it onto our website.
The next part is React helps us create
websites easier. So now let's learn how
to use React.
We'll go back to VS Code
and we're going to scroll down and these
two lines of JavaScript at the bottom
sets up React. So let's go through this
step by step. In the first line, we're
using document.query query selector to
get an HTML element from the website and
put it into our JavaScript. As a review,
this is a feature of JavaScript called
the DOM or the document object model.
Basically, JavaScript gives us this
document object which sort of combines
JavaScript and HTML together. It lets us
get HTML elements from the page and put
them into our JavaScript and it also
lets our JavaScript modify HTML elements
on the page. So the DOM or the document
object sort of combines HTML and
JavaScript together and it lets the two
languages interact with each other.
Don't worry, you don't need to know a
lot about the DOM to learn React. I'm
just explaining what this code does so
you understand what's going on here.
So the code document.query selector lets
us get an HTML element from the page and
put it into our JavaScript.
Inside these brackets, we tell the
computer which HTML element we want to
get from the page. So if we start with a
dot, this means we're going to look for
a class. And here we're looking for the
class js-container.
Up here, this div element has the class
js-container.
So, it's going to take this element and
put it into our JavaScript. And finally,
we're going to save it inside a variable
so we can use it later.
Next, let's go to the second line of
code and react.create
routt basically sets up React
To set up React, we have to give it an
HTML element. So, we're going to give it
the element that we saved up here, which
is this div element. So, basically the
way this works is that this element is
going to act as a container.
Everything that we create with React is
going to be displayed inside this
element or inside this container. The
reason React uses a container is because
it keeps things organized.
Everything inside this element will be
controlled by React and React will not
affect anything outside of this element.
So it keeps things isolated and
organized.
So after we set up React with a
container, we can start using the
features of React.
One feature of React is render. Render
means to display something. So render
lets us display something inside this
container or inside this element. Now
between the brackets of render, we're
going to tell React what to display
inside the container. So right now we
told it to display the text welcome to
super simple dev react course. And if we
go back to our website and open the tab
for our website
and after we open the console, this time
we're going to go to the elements tab.
So this lets us see the HTML that's
currently on the page. We're going to
open this body element and inside we can
see our container and you can see that
React rendered or displayed the message
welcome to super simple dev react course
inside our container. So we'll go back
to our code
and that's how we set up and use React.
First we give it a container and then we
can display things like a message inside
this container.
Before we continue, let's review the
rest of the code in this file to make
sure that we understand every line of
code. So, the HTML at the top here
as well as the bottom here.
This HTML is called the HTML structure.
As a review, this is a standard
structure that we follow when writing
HTML.
At the top, dock type HTML tells a
computer to use a modern version of
HTML.
The HTML element represents a website.
So all the code for our website should
go inside the HTML element. Now every
website is split into two sections. the
head section and the body section. The
head section generally contains things
that are not visible on the page. For
example, the title element sets the text
at the top of the tab. So, this is not
visible on the page. So, we put this
inside the head.
The body section generally contains
things that are visible on the page. For
example, the div element will be visible
on the page. So we put it inside the
body.
Finally, we usually put our script
elements at the bottom of the body
because we want our HTML to be created
first and then our JavaScript can modify
the HTML.
So that's a review of the HTML
structure. This is a standard structure
that we follow when writing HTML.
So now we understand almost every line
of code in this file. This is just the
HTML structure that we have to follow.
This is a container that we give to
React to keep things isolated and
organized.
This is an example of an external
library and this loads the React
external library or loads the code for
React.
And this sets up and uses React.
The last two lines that we haven't
learned yet are these two lines right
here. So here we're loading another
external library. And this external
library is called Babel.
So again if I open this URL in my
browser copy
and in my browser going to create a new
tab and at the top paste and press
enter.
You'll see that this website contains a
bunch of JavaScript code and this is the
code for another external library called
Babel.
So we'll go back to VS Code and let's
learn what is the Babel external
library.
Babel is known as a JavaScript compiler.
So it basically translates other
languages into JavaScript.
So why do we need Babel? When using
React, we actually don't use normal
JavaScript. We use an enhanced version
of JavaScript called JSX.
JSX stands for JavaScript XML. It's the
same as JavaScript, but we can also
write HTML directly in our JavaScript
code. So, it's just JavaScript with
extra features. So, let's do an example
of JSX to learn how to use it. Inside
the script element at the bottom, we're
going to create a new variable using
const and let's call it button
equals. And now let's create a button
HTML element. So here we're going to
type HTML directly less than button
greater than and then less than /button
greater than.
So this is actually HTML code and we're
writing it directly inside our
JavaScript. So this HTML code creates a
button and then inside our button we can
put the text hello.
So this code here is actually using JSX.
So JSX works the same way as JavaScript
except we can also write HTML directly
in our JavaScript code.
So, what does this code do? It's
actually pretty straightforward. This
code creates a new button element inside
our JavaScript and then we save it in a
variable.
We can actually do this with normal
JavaScript as well. We can use the DOM
and we can create a button element in
our JavaScript like this. So you can
think of this JSX code as a shortcut for
this JavaScript code.
So that's JSX. JSX is an enhanced
version of JavaScript. So it's the same
as JavaScript, but we can also write
HTML directly in our JavaScript code. So
when using React, we usually use JSX
instead of normal JavaScript because, as
you can see, JSX is simpler.
Now there is one problem with JSX which
is our web browser doesn't understand
JSX. It only understands normal
JavaScript.
In order to use JSX we need to translate
it into normal JavaScript first and then
our web browser can understand this
code.
To do that we use the Babel external
library. Babel translates JSX into
normal JavaScript so our web browser can
understand it. To use Babel, we need to
do two steps. First, we load the Babel
external library, which is what we do
here. And then when we want to translate
something into JavaScript, we have to
give the script element an attribute
type equals text/babel.
So this attribute tells Babel to
translate all the code inside here into
normal JavaScript.
So that's what these two lines of code
do. First, we load the Babel external
library and then we tell Babel to
translate the code from JSX into normal
JavaScript so our web browser can
understand it. So now we understand all
of the code in our starting file. And
again, this is the minimum amount of
code that we need to set up React.
Next, let's learn some more features of
React. So, we'll scroll back down. And
currently, we're using React to display
some text inside this container. Now, in
addition to text, we can also display
HTML elements inside this container. So
to do that, we're going to remove this
string
and instead we're going to give render
an HTML element.
So up here, we actually created an HTML
element or a button. So we're going to
give this to the render function. So
here we're going to give it the button.
And now it's going to display this
button inside our container or inside
this div here. Let's save and we'll open
the browser
and open the tab for our website. And
you'll see it displayed the button with
the text hello on the website.
And if we check the elements tab, you
can see that React displayed the button
inside our container.
We'll go back to our code.
So that's what this code does. It
displays an element inside this
container.
Now let's do another example. Let's
display a different HTML element inside
this container. So below this button,
let's use JSX to create a paragraph
element. So first we'll create a new
variable using const and we'll name the
variable paragraph
equals and we'll create a paragraph
element using the code less than p
greater than less than /p greater than.
So this html code creates a paragraph or
a paragraph of text. Inside our
paragraph, let's just put paragraph of
text.
And now let's display this paragraph on
our website. So inside render, instead
of the button, we're going to render the
paragraph
and save.
If we open our website,
you can see it displayed a paragraph of
text. If we go into the elements tab and
we open this div container,
we can see that React displayed this
paragraph element inside this container.
So let's go back to our code. And that's
basically how we use React. We give
React a container and then we can
display an HTML element inside this
container.
Next, we're currently using React to
display one element at a time on our
website, which is not that useful. So
now we're going to learn how to use
React to display multiple elements on
our website. So one thing we can't do is
give render multiple elements. So this
is not supported. We also can't save
multiple elements inside a variable.
This is also not supported. Instead, we
need to use another HTML element called
a div element. So, under our paragraph,
let's create a new variable using const
and let's name it div and make it equal.
And we'll create an HTML div element
using the code less than div greater
than less than /d greater than.
So this is the HTML code to create a div
element. As a review, the div element
represents a container. The purpose of a
div element is to contain other elements
like buttons and paragraphs. So that's
actually why we used a div element up
here. This element is a container. It's
going to contain everything that we
create using React. So let's go back
down.
Inside our div element, we can put other
HTML elements like a button. So, let's
actually select this code and we'll copy
and then inside this div, paste.
And let's also put a paragraph element
inside our div. So we'll select this
code for the paragraph element and we'll
copy
and our div paste.
So this code works because a div is
considered as one element. So we're just
taking one element and saving it in one
variable which is supported in
JavaScript. The only thing special about
this is that this one element can
contain other elements inside.
Next, we're going to give this div to
the render function here. So, instead of
the paragraph, we're going to give
render our div and save.
And if we check our website,
you can see that React displayed
multiple elements on the website, a
button and a paragraph. If we look at
the elements tab and open this div
container,
you can see that React displayed our div
inside this container.
Let's go back to our code. And that's
how we display multiple elements on a
website using React.
First, we group the elements inside a
div element. And then we render the div
element.
Before we continue, we're going to do
some code cleanup. When we have multiple
lines of HTML like this, a best practice
is to add brackets around it. So, at the
front, we're going to add an open
bracket and at the end, a closed
bracket.
And we're going to put the HTML on its
own line. So, here we have JavaScript
and HTML together. We're going to add a
new line here by pressing enter. and
we're going to put the HTML on its own
line. Same thing here. Click here and
press enter to put the HTML on its own
line.
Next, we have two elements that are
inside a div. So, we're also going to
give this line an indent by pressing
tab. And then, we're going to give this
line an indent by pressing tab. So that
it's easy to see that these two elements
are inside this div element.
So this is how we should format our code
when we have multiple lines of HTML.
Another way to think about this is
inside here, you're actually just
writing HTML normally.
So don't worry, the more that you use
React, the more you'll get used to this
format.
So let's save this file.
Now that we learn the basics of React,
let's talk about how React helps us
create websites easier.
If we look at this code, creating a
website with React feels natural. It's a
lot simpler than using the DOM feature
in JavaScript. We can just create the
HTML elements we want directly and then
give it to React and React will display
it on the website.
Another benefit is JSX lets us find
errors easier.
For example, if I misspell button, it
will actually tell me that these two
don't match because this is an actual
element rather than just text or a
string. So, it makes it easier to find
errors when we're coding. So, I'll add
the O back.
Another benefit is we can insert values
inside our JSX elements. For example,
inside this paragraph, we're going to
type space and we're going to insert a
value here by typing open curly bracket
close curly bracket. And inside here, we
can give it any JavaScript code. For
example, 2 + 2. So this will calculate 2
+ 2 and then insert it into this
element. If we save
and then check our website,
we can see that it calculated 2 + 2
which is four and inserted it into this
paragraph element. So we'll go back to
our code and that's another benefit of
using React. We can insert JavaScript
code directly into our JSX elements. So
this is similar to string interpolation
where we can insert values into a string
except here we're inserting values into
actual HTML elements. So those are three
ways that React helps us create websites
easier. Number one, it's more natural.
We can create the elements that we want
and then just give it to React and it
will put it on the website. Number two,
it helps us find errors easier because
these are actual elements. And number
three, we can insert our JavaScript code
into our elements. So this helps us use
JavaScript and HTML together more
easily.
Now, React has many other features that
helps us create websites easier, but
we're going to learn those features
later on as we go through the course.
The last thing we're going to do is
we're going to scroll up and we're just
going to remove this example external
library
and save
so that we just have the code that we
need for React.
And that's the end of this lesson. In
this lesson, we learned that React is an
external library that helps us create
websites easier. We learned how to load
the React external library. We learned
how to set up React and use render. We
reviewed the basics of HTML and
JavaScript.
We learned JSX, an enhanced version of
JavaScript.
We created elements directly with JSX.
And we learned how to insert values into
our JSX elements. Here are some
exercises to help you practice what we
learned in this lesson. You can find the
solutions to these exercises in the
video description.
In this lesson, we're going to learn two
of the most important features of React,
which are components and props. To learn
this, I actually prepared a project that
we can do for this lesson. We're going
to go to our browser
and we can delete these extra tabs for
now.
And we're going to create a new tab.
And at the top, we're going to go to
super simple.dev/projects/
chatbot and press enter.
This is a chatbot project. We can send a
message to a robot up here and the robot
will respond to our message. For
example, we can click in here and type
hello chatbot and then press send.
And the robot will respond with hello,
how can I help you? Now, if we scroll to
the bottom of this page, we can also
move the text box to the bottom by
clicking this link.
So, a lot of chatbot applications use
this design where the text box is at the
bottom. However, because we're watching
a video, this text box might get cut off
or it might be covered by the video
progress bar. So, just for this video,
we're going to click this again and
we're going to start with a text box at
the top.
Next, this is a simple chatbot and
currently it can only do three things.
get today's date, flip a coin, and roll
a dice. For example, up here, we can
type, "Can you get me today's date?"
and press send.
And it will respond with today's date.
And let's try typing, "How about flip a
coin?" and press send.
and it will respond with heads or tails.
Finally, let's type okay, thank you and
press send.
And it responds with no problem.
So, this is a chatbot project we're
going to work on for the next few
lessons. Now, this is a simple chatbot
and it can only do these three things.
But in the future, we can also switch
this to a more powerful AI that can
respond to any message we send.
But for now, we'll just use this simple
chatbot to learn React. Now, let's use
React to build this chatbot project.
We'll go back to VS Code
and let's make a copy of React Basics.
So, first we'll select this file and
then rightclick,
copy.
And inside here, we're going to
rightclick and paste.
And let's rename this file. So, we'll
rightclick and rename
and rename it to chatbot.html
and press enter.
And let's close the React Basics files
for now.
So, we're going to start with the same
code as the React Basics file, except
we're just going to change the title up
here. So, we'll remove React Basics and
just change it to chatbot
and save.
And now, let's open this file in our
browser. We'll rightclick,
open with a live server.
And it should say chatbot in the tab up
here. So now we can close the React
basics tabs which are these two here.
And we'll go back to VS Code.
And now we're ready to begin the chatbot
project.
First we're going to learn one of the
most important features of React called
components. A component is just a piece
of the website.
For example, let's go back to our
browser and open the final chatbot
project.
So looking at this project, we can split
it up into different pieces. One piece
can be the text box and the button at
the top and another piece are each of
these chat messages.
So these are called components. A
component is just a piece of the
website. Now, when building websites,
it's better to split up the website into
pieces or components so that we can work
on a small piece of the website at a
time.
Now that we know what components are,
let's create our first component in
React. So, we mentioned that one way we
can split up this website is to have one
component at the top for this text box
and the button. So, let's create a
component for this in React. We'll go
back to our code
and we'll scroll down and first let's
remove the example button and paragraph
that we used. So, we'll select this and
remove it.
And to create a component in React,
we're going to use a function. So we'll
type function. And now we're going to
name this component. Since this piece of
the website is for inputting a message
and sending it to the chatbot, let's
name this component capital C chat
capital I input brackets and curly
brackets.
Now in React the component name must
start with a capital letter. So make
sure that chat input starts with a
capital C. This is also known as Pascal
case where each word in the name starts
with a capital letter.
Next this function will return some
HTML. So we're going to type return and
we're going to return the HTML for this
piece of the website. So this piece of
the website has a text box and a button.
So let's type brackets and press enter
between these brackets.
And to create a text box, we're going to
use the HTML element less than input
greater than. And we also need to type
less than /input greater than. Now you
may notice that in normal HTML input
doesn't need this closing tag. However,
JSX is more strict than normal HTML. So,
all elements need a closing tag,
including input. Now, there's actually a
shortcut we can use here. If there's
nothing inside an element, we can
actually remove the closing tag.
And at the end of this opening tag, we
can just type space and then slash. So,
this code is a shortcut for this code.
And this is called a self-closing
element. So in JSX we have to either
have a closing tag or use this
self-closing element shortcut.
Next, this piece of the website also has
a button. So let's also create a button
element using less than button greater
than less than /button greater than. And
inside this button we have the text
send.
And now we're going to get an error here
because we're trying to return two
values or two elements from this
function. But we can only return one
value from a function. To solve this
problem, we can use a div element like
down here to group these two elements
together.
So above this, let's create a div
element.
And at the bottom, less than /d greater
than. And let's also add indents before
these two lines. So we'll click here and
press tab. And also click here and press
tab.
So this shows that these two elements
are inside this div element. And now
this code no longer has an error because
we're returning one value from this
function.
Now that we created this component,
let's learn how to display it on the
website. If we scroll down, right now
we're using React to display this div on
the website. So all we have to do is to
insert our component inside this div and
it will be displayed on the website. So
one way to do this is to use curly
brackets to insert something like we did
before. So here we'll type curly
brackets. And now we're just going to
run this function
capital C chat input and brackets.
So this will run the function and it
will return this HTML from the function
and then the curly brackets will insert
the HTML into the div and then display
it on the page.
So, as you can see, we can put any
JavaScript code between these curly
brackets. As long as this code results
in a value, we can insert it into this
HTML.
Let's remove the button and the
paragraph that we used as an example
and save.
And let's check our website. We'll open
the browser and go to our chatbot
project. And now we created the elements
for the top section of the chatbot
project, the text box and the send
button. So don't worry about how it
looks for now. Later in the course,
we're going to style this with CSS and
make it look like the final project.
Let's go back to our code.
And next, React has a special syntax we
can use to insert a component. Instead
of using curly brackets and running the
function, we can type this code less
than and then the name of the component
capital C chat input greater than and
then less than slash chat input greater
than.
So this is called the component syntax.
This does the same thing as the code
above. It runs the chat input function
and then inserts the result into the
HTML.
If we save
and we check our project, you'll notice
that that syntax does the same thing and
it creates another text box and button.
Let's go back to our code.
And again, this code does the same thing
as this code. Now this syntax has a big
advantage.
This actually looks like an HTML
element. It has an opening tag and a
closing tag. So you can think of this
like we're creating our own HTML element
called chat input.
HTML provides us with some default
elements like div, input and button. And
now using React, we can actually create
our own HTML element like chat input.
Then we can use our own HTML elements to
build the website instead of just the
default HTML elements. And this is
actually one of the main ideas of React.
We can create our own HTML elements. So
when using React, we should use this
component syntax instead of running the
component function directly because this
syntax lets us create our own HTML
element.
And again, we can use the self-closing
element shortcut like we did up here. If
there is nothing inside this element, we
can remove this closing tag.
And inside the opening tag at the end,
we can type space and slash.
And now we can remove this example code
above.
And let's save and check our project.
And that creates the top section of the
chatbot project.
So go back to VS Code.
And we mentioned in the previous lesson
that React helps us create websites
easier. And this is another way that
React helps us create websites easier.
It lets us split our website into
smaller pieces or components. And this
lets us work on a small piece of the
website at a time.
Before we create the rest of the
project, we're going to improve our code
a little bit. First, notice that in this
component, we're using a div to group
these two elements together. However,
this is also going to insert an extra
div element into our website. So, if we
go to our website
and rightclick and click inspect,
and we're going to go to the elements
tab, and we're going to go to our
container here, and we're going to
expand it.
So notice here that we have a bunch of
extra divs on this website. So what if
we don't want to insert these extra
divs? What if we just want to insert the
text box and the button on our website?
Let's go back to our code and learn how
to do that.
React has another way to group elements
together called a fragment. To use a
fragment, we can remove the word div.
and div from the closing tag and just
have a less than greater than and a less
than slashgreater than. So this is
called a fragment and it groups the two
elements together. So we can return it
from the function but it won't insert an
extra div. So, if we save this code and
then go to our website
and take a look at the HTML,
you'll notice now we have one less extra
div on the website.
Let's go back
and we can also use a fragment down
here. If we don't want to insert this
extra div, we can remove it and remove
it at the bottom and just use a
fragment. If we save and check the
website,
now we no longer have those extra divs.
We have our container and we just
inserted the text box and the button.
So that's fragments. It allows us to
group elements together without creating
an extra div.
Let's go back to our code.
And since this variable no longer
contains a div, let's rename it. So
right now we're building a chatbot
application or an app. So let's rename
this variable to app instead. And here
as well, we're going to render the app
and save.
So again in React, when returning
multiple elements or saving multiple
elements, we can use a fragment to group
them together. And this makes our HTML a
little bit cleaner because it doesn't
create an extra div element.
Next, another improvement we can make is
to add a placeholder to the text box at
the top. So the gray text inside the
text box is called a placeholder. It
tells us what to type inside the text
box. And when we start typing, it will
disappear.
To create a placeholder, we give this
input element an attribute. So at the
end, we're going to type the attribute
placeholder
equals double quotes.
And then inside these double quotes,
we're going to put the text that we
want, which is send a message to
chatbot.
If we save this code
and look at our website,
now we have a placeholder in the text
box. And when we start typing in it, it
will disappear. So the placeholder is
working. Now there is one problem here,
which is if we remove this text, you'll
notice that this placeholder is too long
and it's getting cut off. To fix this,
let's make this text box wider. We'll go
back to our code.
And to make this input wider, we're
going to give it another attribute. So
at the end, we'll type another attribute
called size equals double quotes. And
this sets how many characters can fit in
this input. By the way, a character is
just a letter, number, or symbol.
Let's set the size to 30 characters and
save and take a look.
Okay, so that looks pretty good for now.
Again, don't worry about how this looks.
We'll style it later in the course using
CSS.
So, we just created our first component
or our first piece of the website, which
is the section at the top. Now, let's
get some practice and create more
components.
Let's go back to the final chatbot
project
and let's ask ourselves how can we split
up the rest of this website into pieces.
Another piece of this website could be
one chat message here. So let's create a
component for this piece of the website.
We'll go back to VS Code
and to create a component we're going to
use a function. So down here, let's
create a function
and let's name it capital C chat capital
M message
brackets and curly brackets. So remember
a component name must start with a
capital letter and we use Pascal case.
So each word starts with a capital
letter.
Now inside this function, we're going to
return the HTML for this piece of the
website or this component.
So let's also type brackets and enter.
So we can write the HTML on multiple
lines. And now each chat message has two
things, some text and a profile image.
Since we have multiple things inside
this component, let's group them
together using a fragment. So we can
return one value from this function. So
we'll type less than greater than enter
and then less than /g greater than to
create a fragment. And now inside here
each message has some text. So let's
create the first chat message in our
project. We'll go back to the final
project.
And let's just copy paste the text from
the first message here which is hello
chatbot. So we'll select this and then
copy by pressing control C on Windows or
command C on Mac.
And then inside our code
in the chat message component we're
going to paste by pressing controlV on
Windows or commandV on Mac.
And let's fix the indent by pressing tab
at the start.
Next, each chat message has a profile
image. To create an image, we can use an
HTML element called img. So, let's
create a new line. And we're going to
type less than img greater than and then
less than / img greater than. So,
remember that in JSX, every element has
to have a closing tag. And again, we can
use the self-closing element shortcut
like we did down here. If there's
nothing inside this element, we can
remove the closing tag and then just add
a space and a slash at the end of the
opening tag. And now we have the two
things that we need for each chat
message, the text and an image.
Next, we need to tell the computer which
image to load. Right now, if we look at
our final chatbot project, we have two
images that we use, but we currently
don't have these in our project. So,
let's download them. We're going to
rightclick this first image and then
click save image.
And we're going to find the folder that
contains all of our code. So, for me,
it's on the desktop
and it's in the folder React-Course.
and we're going to save it inside of
this folder.
And same things for this robot image.
We're going to rightclick
and click save image.
Go to the React-Course folder. And we're
also going to save the robot image.
And now if we look at our code,
we should have two images inside our
project. User.png png and robot.png.
And now let's go back to our code.
To load an image on the website, we need
to tell the computer which image to
load. To do that, we're going to give
this image element an attribute called
src or source equals double quotes. And
inside these double quotes, we're going
to tell the computer which image to load
for the first chat message. The image is
the user image. So let's type this file
name. userpng.
So this will look for a file called
user.png
beside the current HTML file. This is a
current HTML file. So we'll look for
user.png beside it, which is right here.
and then it's going to load this image
on the website.
Okay, so we created a component for a
chat message. Now let's insert this
component on the website. We're going to
scroll down
to the app and let's insert this
component using the component syntax
like we did up here. So we'll type a new
line and type less than and then the
name of the component which is capital C
chat
capital M message.
And currently we don't have anything to
put inside this component. So we use the
self-closing element shortcut like we
did up here. So now let's save
and check our website
which is this tab. And let's close the
console so we can see it. And we created
a chat message.
However, we have a few problems here.
The first problem is that the profile
image is too big. To make it smaller,
we're going to go back to our code
and inside the img element, we're going
to give it another attribute called
width equals double quotes.
And let's try setting the width to 50
and save. And then check our website.
And that looks close enough.
Another problem is the chat message is
appearing on the same line as the chat
input, but in the final project, we want
it to appear below. To fix this, we'll
go back to our code
and inside the chat message component,
instead of using a fragment to group
these elements together, we're going to
change it back to a div. So, inside
we'll type div and inside here /d.
The reason we're using a div is because
in HTML, a div is known as a block
element. A block element will always
take up an entire line by itself. So if
we group this in a div element, instead
of appearing beside the chat input, the
div is going to take up an entire line
by itself. So it's going to take up the
entire line under the chat input. So
let's save this code and then check our
website.
So now this div is taking up this entire
line. If we rightclick and click inspect
and then click this arrow icon in the
top left and then click on this div,
you can see that this div now takes up
this entire line. So now we have the
layout that we want. So in React, we
still use divs for layout purposes.
If you want to learn divs, layout, and
HTML in more detail, you can check out
my HTML and CSS full course in the video
description.
So now we created our first chat
message.
Next, let's create the second chat
message. We'll go back to our code
and instead of creating a whole new
component, we can actually reuse our
chat message component. Components are
actually designed to be reusable.
To reuse this component, we don't want
the message to be hello chatbot every
time. We want to be able to display
different messages in this component. To
do that, we can give our component an
attribute. So down here, we're going to
go to the chat message component and
we're going to give it an attribute. So
this works just like HTML attributes.
We're going to give our attribute a
name. Let's call it message
equals double quotes. And inside these
double quotes, we're going to give the
attribute a value.
Let's put the text for the first message
which is hello chatbot. So let's select
this code and then copy
and we're going to paste it inside here.
So now we have an attribute called
message with a value hello chatbot. So
again you can see that this syntax looks
like HTML. We can even add our own
attributes.
Now that we added this message
attribute, how do we access it inside
this component and use it? To do that,
we're going to use a feature called
props.
Every component function gets one
parameter up here called props.
This props parameter is an object and it
contains all the attributes that we give
to this component. So up here, let's
actually console.log
props to see what it looks like. Let's
save and then open our website and check
the console.
And you'll see that props is an object
and it contains the attributes that we
gave to our component. So here we have
the message attribute and it has a value
hello chatbot. So the attribute name is
saved as a property and the attributes
value is saved as a value of this
object.
So let's go back to VS code
and using this props object we can
access our attributes. By the way props
is short for properties. We call this
props because the attributes are saved
as properties in this object.
So now to access the message attribute
we can remove this and type props
dot and the attribute name which is
message
and let's save this in a variable so we
can use it later. So at the front we'll
create a variable using const name name
it message
equals props dossage
and we'll add a new line to separate the
code a little bit.
Now instead of displaying hello chatbot
every time let's display whatever is in
the message attribute. So we'll remove
this
and let's insert this variable into this
element. To do that we can use curly
brackets and type the variable name
message.
So again we can put any JavaScript code
between these curly brackets and as long
as it results in a value it will insert
it into this element. So now let's save
and we'll check the website
and it displays a message hello chatbot.
That's the message attribute that we
gave it.
Let's go back to our code.
So that's props. Just like a normal HTML
element, we can give attributes to our
component and then access these
attributes using this props object.
So props are really useful because props
make our component reusable.
For example, let's try creating the
second chat message. To do that, we can
just create another chat message
component. So down here, let's type less
than chat message/grater
than.
And we just need to give it a different
message attribute. So here we'll give it
an attribute message equals double
quotes. And we'll copy paste the second
message in the chatbot project. We'll go
to our browser
and go to the chatbot project and let's
copy and paste this second message.
We'll select it and then copy.
And inside our code in the message
attribute, we're going to paste.
So this will save the message hello how
can I help you inside props and then we
get it out of props and insert it into
the component. Let's save and check the
website
and go to our tab.
And now we created the second chat
message. So let's go back to our code.
And you can see that props make our
component reusable. We can reuse this
component, but just give it a different
attribute or prop and it will display a
different message.
Let's get some practice and use props to
create two more chat messages. Feel free
to pause if you want to try it yourself
first.
So down here, let's create our third
message using less than chat
message/grater
than. and we'll give it a message
attribute equals double quotes and we'll
copy paste the third message. We'll go
to the chatbot project
and select this third message and then
copy.
And in our code inside the attribute,
we're going to paste.
And finally, let's create the fourth
message less than chat message
slashgreater than and then the message
attribute equals double quotes and we'll
copy paste the fourth message which is
this one. So don't worry if your
messages are different from mine. We're
just doing an example. So we'll select
this and copy.
And inside here, we're going to paste
and save.
And now, if we check our website
and go to our tab, you'll see that we
now have four chat messages in our
project. So, that's how we use props to
reuse the chat message component.
Next, in the final chatbot project,
notice that these two messages are
different. These two messages are from
the chatbot. So there are two
differences here. The profile image is a
robot and the image is on the left. To
create this, we can add another prop to
chat message. Let's go back to VS Code
and for each chat message, we're going
to add another attribute.
And let's call this attribute the sender
equals double quotes.
This attribute tells us who sent the
message. And we can use this to
determine which image to load and where
to place the image. So if we send the
message, let's make the sender the user.
And for the second chat message, we're
going to add another sender attribute
equals double quotes. And the second
message is from the chatbot. So let's
make the sender attribute the robot.
And we'll do the same thing for the
third and fourth message. We'll give it
a sender attribute.
The third message is from the user. So
let's make the sender user.
And the fourth message sender equals
double quotes. This message is from the
robot. So let's make the sender robot.
Next, let's access the sender attribute
inside our component. To do that, all
the attributes are saved inside this
props object. To access the sender
attribute, we can type props dot sender.
So this gives us the value of the sender
attribute which is either user or robot.
So let's save this in a variable so we
can use it later. Type const and let's
call it sender equals props.
So now that we have the sender
attribute, let's use it to decide which
profile image to load and where to place
this image. To do that, we can just use
an if statement.
So inside here, we can type if brackets
and curly brackets.
And inside these brackets, we're going
to check if the sender
is equal to the string robot.
By the way, by default, if the attribute
just has double quotes like this, the
value is a string. So here the value is
going to be the string user or the
string robot.
So now inside our component, if the
sender is the robot, we're going to
return some different HTML.
So let's type return brackets. So we can
write this HTML on multiple lines. And
let's just copy paste the HTML from down
here and modify it. So we'll select this
HTML and then copy
and then inside this return we're going
to paste.
And let's also select these lines and
press tab to fix the indenting.
So the first thing we need to change if
the sender is a robot is that we want to
load the robot image instead.
So, we already downloaded the robot
image here. To load it, we're just going
to change the src attribute or the
source attribute of this image. So,
we're going to change this from user to
robot.png.
And we also want this image to be on the
left. So, let's just move this image
before the message. So we'll select this
code and then cut by pressing control X
on Windows or command X on Mac.
And then before the message we're going
to paste by pressing controlV on Windows
or commandV on Mac.
And we can remove this extra new line.
So as you can see inside a component we
can use any JavaScript feature like if
statement and we can return a different
HTML and whatever we return will be
inserted inside the element here. So now
let's save this code
and then check our website
and then open our tab
and you can see that now we have two
messages from the chatbot. that loads
the robot image and it puts the image on
the left.
We'll go back to our code
and using this sender prop, we're able
to reuse this component to create a chat
message from the robot. So again, props
make our component reusable.
And that's it. If we scroll down,
using components, we split up the
website or the app into smaller pieces
like the chat input section at the top
and each chat message. And we created
all the HTML that we need for this
project.
The last thing we're going to learn in
this lesson are some shortcuts that are
commonly used in React, and we can use
these to clean up our code.
First, let's scroll up to the chat
message component.
So, instead of doing con message equals
props message, we actually have a
shortcut for this in JavaScript. So,
down here we can just type const curly
brackets and inside we can type message
and make it equal to props.
So this takes the message property out
of this object and saves it in a
variable called message. So this does
the same thing as this line above. This
code is a shortcut for this code. And
this shortcut is called dstructuring
because we're taking stuff out of this
object. We're deconstructing it. We can
also use this shortcut with the sender
property to add another property to take
out of this object. After the first
property, we can type comma and the
second property sender.
So this will get the message property
and the sender property out of this
object and it will save it in a message
variable and a sender variable. So this
line of code is a shortcut for these two
lines above.
So now let's actually turn these two
lines into comments or comment out these
lines. At the front we're going to type
double slash and at the front here we'll
type double slash.
By the way, if we start with double
slash, it will turn this code into
comments and it will be ignored by the
computer.
So, we'll just keep this here as a
reminder that this is a shortcut for
these two.
Next, JavaScript has an even shorter
shortcut for this. Since props is a
parameter up here, we can just
dstructure it directly up here. So here
instead of the props object we can just
type curly brackets directly
and then type message
and sender.
This takes the message and sender
properties directly out of the first
parameter and then saves them in a
variable called message and a variable
called sender. So it does the same thing
as this code down here, but it's an even
shorter shortcut. We're dstructuring the
parameter directly at the top. So this
shortcut is used a lot in React
tutorials and documentation. So it's
useful to know how this works.
So let's comment out this line here at
the front. We'll type double slash.
So we remember that this code is a
shortcut for this line of code and these
two lines of code.
Now, let's save and check our website to
make sure that everything is still
working. So, that looks good.
We'll go back. And that is a
dstructuring shortcut. It allows us to
take properties directly out of an
object.
Next, we're going to learn how to use if
statements directly inside JSX.
So currently we have some JSX here and
we put an if statement outside of this
JSX.
However, this means we're duplicating
some code like the div and the message.
To make this code more reusable, we can
actually move this if statement directly
inside the JSX down here. So what we
want to do is if the sender is a robot,
we want to put the image before the
message. So down here, let's go before
the message and press enter. And we're
going to type curly brackets and we're
going to insert the if statement
directly inside here. So here before the
message we want to do something like if
the sender is equal to the string robot
we're going to insert this image.
However we can't actually use the word
if inside of these curly brackets.
Instead we need to use another feature
of JavaScript called a guard operator or
and.
In JavaScript, you can write value one
and value two. If value one is true,
then the result will be value two. So
this works just like an if statement
except we can write it on one line and
it results in a value. So if you want to
learn more about this feature, I cover
it in the booleans lesson of my
JavaScript course and you can check out
that in the video description.
For now, the only thing we need to know
is we can use and as sort of an if
statement in our JSX.
So, first let's remove this
and then we're going to use and to
insert this if statement directly inside
the JSX.
So, the first value is going to be our
if condition, which is sender equals the
robot. So we'll check if the sender is
equal to the string robot
and then we're going to use and.
So if this is true, the result is going
to be the second value here. So here if
the sender is a robot, we want to insert
the robot image. So let's just copy and
paste this code. We're going to select
this
and then copy it.
And then down here after and we're going
to paste.
So again the way this works is if the
value on the left is true then the
result will be the value on the right.
So this and is sort of a shortcut for
this if statement and it lets us insert
if statements directly inside our JSX.
So let's actually comment out this if
statement out here. So we remember that
this code is a shortcut for this code.
So here before the if statement we'll
type slash and star and after the if
statement we'll type star and slash and
remove the indent. So this is known as a
multi-line comment. All the code between
these two stars will be ignored by the
computer. So now let's save
and check our website.
And as you can see, if the sender is a
robot, we're going to add an image on
the left before the message. So now, one
problem here is that we're also showing
the user's profile image at the back,
but we only want to show one profile
image. We'll go back to our code
and here we only want to show the user
profile image if the sender is the user.
So let's insert another if statement
down here. Feel free to pause this video
if you want to try it yourself first.
So at the front we'll type open curly
bracket. At the end a close curly
bracket.
And at the front we're going to type the
if condition. So we'll check if the
sender is equal to the string user and
then we'll type ant. So if this is true
then we will show this image. If this is
not true, we will not show this image.
So this code is a shortcut for this
code.
Let's save and check our website.
And it works. The robot image is on the
left and the user image is on the right.
So let's go back.
Using the guard operator or and we can
insert an if statement directly inside
our JSX.
Next, we're going to do some code
cleanup. So, let's scroll up and we're
going to go to the chat input component
first. So, you notice that in here, this
line is a little bit too long. To make
our code easier to read, we can actually
put each attribute on its own line. So,
here we'll type enter to put placeholder
on its own line. And here we'll type
enter to put size on its own line. And
let's also type enter at the back. So
the attributes are on their own lines.
And then let's add an indent in front of
these attributes by pressing tab and
pressing tab. This makes it clear that
these attributes are part of this
element. And we also want to make sure
that these two are vertically aligned.
This makes it easy to see where this
element starts and where it ends.
Next, let's scroll down to the chat
message component. And notice that these
two lines of code with the and are also
a bit too long. To improve this, we can
surround this value with brackets. So
we'll type open bracket and at the end
close bracket and then we can put this
code on its own line. So here we'll type
enter and at the end we'll type enter.
So this will still have the same value,
but the brackets allow us to put the
code on multiple lines. We'll do the
same thing for the second image.
We'll surround it in brackets, open
bracket, and close bracket. And we'll
put this value on a separate line
so that it's no longer too long.
Next, let's scroll down even more to the
app variable. And you'll notice that
these lines are also a bit too long
because of the attributes. Again, we can
put each attribute on its own line. So
here we'll put message on its own line
and sender on its own line. And we'll
put the end of the component on its own
line so that this is vertically aligned
with this. And let's also add indents
before the attributes. So we'll press
tab and tab. So it's easy to see that
these attributes are part of this
component. And we'll do the same thing
for the other three chat messages. So
we'll put this on its own line
and add indents.
And put this on its own line.
Add indents.
And put this on its own line.
And add indents.
and save
and check our website and everything
should still work because we just
changed the formatting of our code. So
let's go back and that's how we avoid
our lines being too long. We can put
each attribute on its own line
and we can also surround a value with
brackets and put it on its own line.
Finally, down here, instead of using a
variable to save our app, a best
practice is to use a component to create
this app.
So here, let's create a component using
function
and we'll name it capital A app
brackets and curly brackets.
And then this component will return all
of this HTML.
So we'll return brackets so we can write
it on multiple lines.
And we're going to move all this code up
here. So let's select this code. And
we'll cut
and inside the return
we're going to paste.
And we can select these lines
and press tab to fix the indenting.
So now we're going to use this component
instead of the variable to create our
app. So down here, let's remove this
variable.
And then inside render, we're going to
create the app. We can type less than
capital A app greater than and then less
than slash app greater than.
So this creates an entire chatbot
application. And then we give this to
React to display on the website.
And again since there's nothing inside
this component, we can use the
self-closing element shortcut. So we can
remove this closing tag. And then at the
end here we can type space and slash.
And now let's save
and check our website.
And it displays the app on the website.
Let's go back to our code.
So a best practice is to use a component
called app to create the website because
it gives us access to extra features of
components like props.
And also notice that we can have
components inside a component. So this
lets us split up a website into smaller
and smaller components or smaller and
smaller pieces.
So again, React helps us create websites
easier because it lets us work on a
small piece of the website at a time.
In the next lesson, we're going to learn
a very important feature of React called
state. State lets us make our website
interactive, and it will let us add new
chat messages to our website.
And that's the end of this lesson. In
this lesson, we learned that a component
is just a piece of the website. We also
learned that components let us create
our own HTML elements. We started the
chatbot project. We split the chatbot
into chat input and chat message
components. We learned props which let
us insert values into components and
make components reusable.
We learned the destructuring and guard
operator shortcuts. We did some code
cleanup and split longer lines into
multiple lines. And we created an app
component which represents the entire
application.
Thanks for watching so far. If you find
this course valuable, you can support
the channel by liking this video,
leaving a comment, and subscribing.
You can also check out the premium
version of this course where you'll get
all the lessons ads free broken down
into small videos as well as additional
lessons and more projects that are not
in the public React course. Currently,
the premium course contains 11 lessons
and I'll be adding more lessons in the
future. You can also get a certificate
of completion, create comments or
questions on specific topics, get
progress tracking, search and course
notes. You can also check out the
membership where you can get this course
ads free separated by each lesson, AI
videos, backend tutorials, and more.
Thanks again, and let's continue with
the course. Here are some exercises to
help you practice what we learned in
this lesson.
In this lesson, we're going to learn two
of the most important features of React
called state and event handlers. And
we're going to use these features to
create the functionality for the chatbot
project.
Before we learn state, we're going to
improve our code a bit. Currently to add
a new chat message we have to manually
type a new chat message component.
Instead of manually typing this code we
can actually use JavaScript to generate
these components.
To do that we're going to do two steps.
The first step is to save the data. Data
means information.
Here the data is the information about
our chat messages like the message and
the sender. So we need to save this data
or this information in our JavaScript.
Let's use a variable to save this data.
At the top of this component, we're
going to create a variable using const
and we'll name it chat messages
equals and we'll save it as an array by
typing square brackets.
As a review, an array is a list of
values. So here we want to save a list
of chat messages. So it makes sense to
save it as an array.
Next, each chat message has multiple
pieces of data, like the message and the
sender. So, inside this array, we're
going to save each chat message as an
object by typing curly brackets.
As a review, an object groups related
values together. So, it's going to help
us group the message and the sender
together.
And then inside this object, we're going
to create a property called message
colon and a string. And we're going to
use this to save the message. So let's
copy the first message. We'll select it
and copy. And we're going to paste it in
here.
And then we'll add a comma. And we're
going to add a sender property colon and
a string. and we're going to save the
first sender which is the user.
So that's how we save the data for the
first chat message in our JavaScript.
Now let's save the data for the second
chat message.
So after the first object, we're going
to type comma and create another object.
I will give this one a message property
as well colon a string. and we'll save
the second message.
We'll select this copy and then inside
here we're going to paste.
Add a comma and a sender property colon
and a string. And the second chat
message is from the robot. So inside the
sender, we'll save robot.
Let's do the same thing for the third
and fourth chat messages. we'll save
them in our JavaScript. Feel free to
pause the video if you want to try it
yourself.
So, for the third chat message, we're
going to add a comma at the end and
another object, a message property, a
string,
and we're going to copy the third
message,
and paste it in here.
and a sender property. The third message
is from the user.
And then we're going to type comma and
another object the message property
colon and a string. And we'll copy paste
the fourth message. So we'll select it,
copy, and then inside here we're going
to paste
and a sender property.
And the fourth message is from the
robot.
So that's how we save the data or the
information for the chat messages.
After we save the data, the second step
is to generate the HTML. So we're going
to use JavaScript to convert this data
into these components. So we don't have
to type these components manually.
To do that, after the data,
we're going to type the name of the
data, which is chat messages.
And this is an array. And arrays have a
feature called dot map and brackets.
As a review, do map lets us go through
each value of an array and convert it
into a new value.
To use dot map, we need to give it a
function. So between these brackets,
we're going to type a function using
brackets, arrow, and curly brackets.
As a review, this is an arrow function.
It mostly works the same way as a
function, but it's shorter. When we give
a function to another function like map,
we usually use an arrow function because
it makes the code a bit cleaner.
This is what React tutorials and
documentations use.
Next, this function gets a parameter. So
at the top, we'll create a new parameter
and name it chat message.
So now dom takes each value in this
array and converts it into a new value.
The way it works is it starts with the
first value and then it saves it in this
parameter and runs this function and
whatever we return from this function
will be the new first value. Then it
takes the second value. It saves it in
this parameter and runs the function.
And whatever we return from the function
will be the new second value. Then it
takes the third value, saves it, runs a
function and whatever we return will be
the new third value and so on. So map
basically goes through each value in
this array, runs a function and converts
it into a new value.
So here we want to convert each chat
message object into a chat message
component. So inside this inner
function, we're going to return a chat
message component by typing brackets
and then here less than chat
message/grater
than to return a chat message component.
Next, each chat message component has
two props, message and sender. So we're
going to add those props to this
component.
So here
we'll create a prop message
equals
and now what do we save in this prop?
Remember that map takes each object in
this array and saves it in this
parameter. So this parameter contains a
chat message object and each chat
message object has a message and a
sender. So we want to save the message
inside this prop.
To do that we're going to type curly
brackets and inside we'll type this
object chat message and get the message
property which is dot message.
This gets the message out of this object
and saves it in the prop.
So why do we use curly brackets here
instead of double quotes? If we use
double quotes, it will save a string
into this prop, which is not what we
want. But if we use curly brackets, it
will save the result of this code into
this prop.
So for the first chat message, the
result of chat message dossage is going
to be the string hello chatbot. So it's
going to take this and save it into the
message prop here. For the second chat
message, the result of this code is
hello, how can I help you? And it will
save this into the message prop and so
on. So using curly brackets we can put
any JavaScript code inside and it will
save the result of this code into the
prop not just a string.
So next each chat message component has
a sender prop. So here we're also going
to add a sender
equals and again we want to save the
sender property of this chat message
object. So we'll type curly brackets and
the object
chat message dot sender.
So this will get the sender property out
of each chat message object and save it
in here. And that's it. Now map will
take each value of this array and
convert it into a chat message
component.
And here's what the result looks like.
Next, we're going to save the result of
this code in a variable. So, up here,
let's type const and we'll name the
variable chat message components equals
this code.
And now we have an array of components
or a list of components.
Finally, we're going to insert this
array into the JSX.
So, down here, we can actually remove
all of these chat message components
because we're generating them now.
And we're going to type curly brackets,
and we're going to insert this array.
In here, we'll type chat message
components.
If we insert an array of components,
React will just display all of these
components on the page. If we save
and then go to our project,
it displays all the chat message
components that we generated with our
JavaScript.
So now we're generating this HTML with
JavaScript and we no longer have to type
out each component manually.
Now, there's one more thing that's
useful to know. Let's go back to our
code.
And there's actually a shortcut that we
can use here. Instead of saving this
result in a variable, we can actually
just insert this result directly in the
JSX.
So, we'll select this code
and then cut.
And between the curly brackets, we're
going to remove the variable and just
paste that code.
And we'll remove the semicolon at the
end.
And we'll select this code and press tab
a few times to fix the indenting.
And finally, we can remove this variable
up here.
Now we're just inserting the result of
this code directly in the JSX.
This shortcut is used a lot in React
tutorials and documentation. So it's
useful to know how it works.
Now let's save
and then check our website.
And everything still works. So that's
how we generate the HTML.
Before we move on, there's actually an
issue that we need to fix here. If we
look at our console and we scroll up,
we'll see an error saying each child in
a list should have a unique key prop. In
React, if we insert an array of
components, we need to give each
component a prop called key. The key
helps React track changes in the array.
So, we should give each component a key.
Let's go back to VS Code
and for each chat message, we're going
to add a prop called key equals.
And this key has to be unique. So, what
should we use as the key?
Usually when we have some data like this
in the real world, each piece of data
should have a unique ID that lets us
identify it. So let's add a unique ID to
each message to match what we would see
in the real world. So for the first
message after the sender, we'll add a
property called ID colon. And let's just
make it a string ID1 to keep it simple.
For the second message, we'll add an ID
with the string ID 2. For the third
message, we'll make the ID ID3. And for
the fourth message, we'll add an ID
string ID 4. So, we'll use these IDs for
practice. They just have to be unique.
And now we'll use this unique ID as the
key. So down here we'll set the key to
be equal to curly brackets and we'll get
the chat message do ID.
So chat message
id.
Again we use curly brackets here because
we want to save the result of this code
as the key. And now each component in
this array will have a unique key. Let's
save and check our website.
And now the error is gone from the
console.
Let's go back to our code.
And now we have a lot of code in our app
component.
To make our code easier to work with,
we're going to separate this code into
smaller pieces.
Notice that this code and this code are
related to chat messages.
So it makes sense to separate these two
pieces of code into a chat messages
component.
So we'll scroll up
above app. Let's create a new component
using function and we'll name it capital
C chat capital M messages
brackets and curly brackets.
And now we're going to move all the code
related to chat messages into this new
component. So we'll select this code
and cut.
And inside here, we're going to paste
and create some new lines. And we're
going to select this code
and cut.
And inside here, we're going to paste.
And at the end of this component, we
need to return the HTML.
So at the end we're going to return open
bracket and we'll remove the closed
bracket for now and we're going to use a
fragment to group all of these
components together. So we'll type less
than greater than and at the end of this
less than/greater than and we'll add the
close bracket at the end. And finally,
we can fix the indenting by pressing
tab. And we'll remove the indent here
and here as well, so that these are
vertically aligned.
Finally, now that we have this chat
messages component, we're going to
insert this into our app. So, we'll
scroll down into app and remove these
lines.
And to insert the chat messages
component, we'll use the component
syntax again. Less than capital C chat
capital M messages
slash greater than.
So now we just separated all that code
into its own component and it makes our
code much cleaner. Let's save
and check our website.
And everything still works. We just
reorganized our code into a chat
messages component.
Okay, so far we saved the data and we
generated the HTML. The last step to
building a website is to make it
interactive.
For example, when we click this send
button, we want to add a chat message to
the website. To make this website
interactive, we're going to use event
handlers.
An event handler lets us run a function
when we interact with a website.
Let's do an example. We'll go back to
our code
and we're going to scroll up to the chat
messages component
and then inside this fragment we're
going to create a new line and let's
create a new button using less than
button greater than and less than/button
greater than and inside this button
let's put the text send message.
So, we'll create a new button for
practice.
Next, we're going to give this button a
special prop. So, here we'll add a new
prop called on capital C click equals
curly brackets.
So, on click lets us run a function when
we click this button. So, above this,
let's create a function to run. So we'll
type function and let's name it send
message brackets and curly brackets
and inside this function let's just
console.log
the string send message.
Now that we have this function we're
going to save this function inside on
click. So between these curly brackets,
we're going to give the name of the
function send message.
So notice that again we used curly
brackets. Curly brackets lets us save
any type of value in a prop including a
function.
Now that we gave on click this function,
when we click this button, it's going to
run this function and console.log this
message. Let's save
and we'll go to our website
and try clicking this new send message
button
and this will run the function and
display the message send message in the
console.
Let's go back to our code
and we'll learn more details about event
handlers.
So on click is known as the event and
send message is known as the event
handler. It does something when this
event happens or it handles the event.
Now there's two other things to note.
The event prop always starts with on and
then the name of the event like click
and the event prop must use camelc case.
As a review, camelc case means the first
word is lowercase and all other words
start with a capital. So that's why on
is lowercase and click starts with a
capital C.
Another thing we should know is that
here we should not run the event handler
function. So we should not use brackets.
So this will run the function and then
the result of the function will be
undefined. and then it's going to save
undefined into on click which doesn't
work. Instead, we should just give the
function directly to on click without
running it.
So that's event handlers and event
handler lets us run a function when we
interact with a website and they make
the website interactive.
Next, when we click this button, instead
of just console.log, log. Let's add a
new chat message. To do that, we can add
a new object to the chat messages array
up here. So, inside this function, let's
remove console.log
and then type the name of the array chat
messages and then use the code.push
and brackets.
As a review, dot push adds a value to
the end of an array. So inside here,
we're going to add another object using
curly brackets.
And each object will have a message
property. So we'll type message colon
and then a string. And for our new
message, let's just make the message
test.
And we'll add a comma. And we'll add a
sender property sender colon a string
and this message will be from the user
comma and we'll give it an ID colon and
let's just use the string ID5.
Now there's one problem with using ID5
in this situation.
Every message that we create when we
click this button is going to have the
ID ID5. But the ID should be unique. To
create a unique ID, we can use some
JavaScript code. So instead of ID5,
we're going to use the code crypto dot
random capital U, capital U, capital I,
capital D, and brackets.
So this is some JavaScript code that
will generate a unique ID string every
time we run this code. So now every
message that we create using this button
will have a unique ID
at the end. Let's create some new lines
and let's console.log
the chat messages array to see if it has
a new message. Let's save
and we'll go to our website
and we'll click send message.
And now inside chat messages, we have
five messages. So we added this last one
here. It has the message test. And
notice it has a unique ID. So we
successfully added a chat message when
clicking this button.
Next, notice that even though we updated
the data, it did not update the website.
So, it did not display a new chat
message component on the website. To fix
this, we're going to learn one of the
most important features of React called
state. State is data that is connected
to the HTML. When we update this data,
it will update the HTML.
Let's go back to our code.
And if we scroll up,
currently chat messages is just a normal
variable. When we update chat messages,
it will not update the HTML.
However, if we convert chat messages
into state, when we update chat
messages, it will update the HTML. So
now let's learn how to convert chat
messages into state.
At the top of this component, we're
going to use this code capital R react
dot use capital S state and brackets.
And between the brackets, we're going to
give it the chat messages data. So,
we're going to select this data
and cut.
and between these brackets we're going
to paste.
So this will convert this data into
state. So now if we update this data, it
will also update the HTML.
So at the bottom here, we can remove the
chat messages variable because we
converted it into state.
Next, react doouse state returns an
array. So at the front, let's save the
result in a variable const array equals
react. State.
This array has two values. To get the
first value, we can click here to
collapse the code for now. And to get
the first value, we're going to type the
name of the array. Array and then square
brackets zero.
So remember, an array is a list of
values and square bracket zero gets us
the first value in the list or in the
array.
So the first value we get from use state
is the current data.
So here chat messages can change over
time. It's going to start off as this
value which is the initial value and
then we might add new chat messages in
the future.
So the first value in this array gives
us the current value of chat messages or
the current data.
Let's save this in a variable so we can
use it later. We'll do const and let's
name it chat messages equals array zero.
So now we have the most current chat
messages and we can use it down here to
generate the HTML.
Next use state gives us a second value
in this array. To get the second value
we're going to type array square bracket
1.
And the second value of this array is a
function that updates this data.
So let's save this function in a
variable using const. And the naming
convention for this function is a use
set. And then the name of the data which
is capital C chat capital M messages
equals this value. And we should also
use camel case here. So the first word
starts with a lowercase and every other
word starts with a capital.
So this function lets us update the
data. In React, we should not update the
data directly like we did down here
using push. We should always use this
function to update the data. And that's
because this function tells React that
the data changed and to update the HTML.
If we update the data directly, React
will not update the HTML.
If we use this function to update the
data, React will update the HTML. So we
should always use this function to
update the data. This is also known as
the updater function.
So now let's give it a try. Instead of
updating this data directly, we're going
to use this updater function by typing
set chat messages and brackets.
And between the brackets, we're going to
put the new value of chat messages.
So the way that this updator function
works is it's going to replace the
entire chat messages array with a new
array. So let's give it a try. First, we
need to make a copy of this array.
In React, we should not modify the data
directly. We should always create a copy
of the data and then modify the copy.
This helps React be more efficient.
To create a copy, we're going to click
between these brackets and create a new
array using square brackets.
And to copy chat messages, we can use
this code dot dot dot and the array that
we want to copy, which is chat messages.
As a review, this is a JavaScript
feature called the spread operator. It
basically takes the values in an array
and then copies them into a new array.
You can think of it like we're taking
the values in this array and then
spreading them out into this new array.
That's why it's called the spread
operator.
The spread operator is used a lot in
React tutorials and documentation. So,
it's useful to know how it works.
So, we created a copy of chat messages.
And now we want to add a new chat
message at the end of this copy because
we're trying to send a new message. To
do that, we can just add a comma at the
end and then add a new chat message
directly using curly brackets.
So each chat message has a message
property colon and we'll give it the
string test for now. And each chat
message has a sender property colon. And
let's make the sender the user.
And we'll give each chat message an ID.
And to create a unique ID we can use
crypto
random capital U capital U capital I
capital D and brackets.
So using the spread operator we made a
copy of the chat messages array and then
we added a value at the end of this new
array.
And now this updater function will
replace chat messages with this new
array. And because we use this updater
function, React will regenerate the
HTML. So it will basically rerun all
this code and it will update the
website. So now let's save
and let's check our website
and we'll press send message.
it will create a new chat message in our
data and it will also update the HTML.
So it will create a new chat message
component and display it on the website.
Now let's go back
and that is how state works. Let's do a
short review. State is basically data
that is connected to the HTML. When we
update this data or we update the state,
it will update the HTML.
To convert some data into state, we use
react doouse state. So here it will
convert this data into state and use
state gives us two values.
The first value is the current data and
then the second value is a function to
update this data. If we use the updater
function, it will also update the HTML.
So don't worry if state is a little bit
confusing at first. The more you work
with state, the more you'll get used to
it. And we'll do more examples of state
in this course and in the exercises so
you can get more practice.
Next, we're going to learn a shortcut
called array destructuring.
Here we get the first value out of this
array and save it in a variable called
chat messages.
Now JavaScript actually has a shortcut
for this. Above this we can type const
and then square bracket equals this
array
and inside the square brackets we can
type chat messages.
So this is similar to object
dstructuring. This gets the first value
out of this array and saves it in a
variable called chat messages. So this
code is a shortcut for this code. We can
also get the second value out of this
array. At the end here we can type comma
and then another variable name. Let's
use set chat messages.
So this gets the second value out of
this array and saves it in a variable
called set chat messages. So this code
is a shortcut for these two lines of
code. And this shortcut is called array
dstructuring because we're taking stuff
out of this array. We're deconstructing
it. Now in array dstructuring the order
matters. So this will always get the
first value out of the array and this
will always get the second value out of
the array.
So now let's comment out these two
lines. So we remember that this is just
a shortcut. So we'll type double slash
at the front and here double slash at
the front.
Now another shortcut we can use is
instead of saving the result of use
state in this variable and then
dstructuring it we can just dstructure
this up here.
So instead of array we can just directly
dstructure using square brackets and
then the first value of u state is going
to be chat messages
and the second value from state is going
to be the updater function which is set
chat messages.
So this code is a shortcut for this
code. We just don't save it in a
variable in the middle.
So at the front of this code, let's also
comment it out using double slash.
So that is array dstructuring. It gives
us an easier way to take values out of
an array.
Now this shortcut is used a lot in React
tutorials and documentation. So it's
useful to know how it works.
Next, instead of adding the same message
test every time, we should add whatever
message is in the text box. So, we'll
learn how to get the text in a text box.
In normal JavaScript, we might use the
DOM to get the input element and then
use a property called dot value to get
the text inside the text box.
However, in React, a best practice is do
not use the DOM manually. That's because
React is managing the website. So, if we
use the DOM manually, it might interfere
with React.
Instead, we should use React features to
get the text from a text box. One way to
do this is we're going to scroll up to
the text box which is inside the chat
input component and it's the input
element here. So to get the text in this
text box we can use a prop called on
capital C change equals curly brackets.
Earlier we learned about the event on
click which runs a function when we
click an element. On change is another
event we can use in React. You can tell
it's an event because it starts with on.
So onchange runs a function when we
change the text inside an input.
So above this let's create a function to
run. We'll type function
and let's name it save input text
brackets and curly brackets because
we're going to save the text inside this
input.
And now let's save this function inside
on change. So between the curly brackets
we'll give it the function save input
text. So again we use curly brackets
here because we want to save a function
inside this prop rather than just a
string. So now every time we change the
text in this input it will run this
function.
Next when onchange runs this function
it's going to give this function one
parameter up here called event.
event is an object and it contains
details about the event or about the
change. So one detail is event dot
target
and this gives us the element that we're
typing in or that we changed. So in this
case it's going to give us this input
element. So React gives us access to
this input element automatically using
event.target. target.
And now to get the text inside this
input, we're going to use the property
value.
So now let's console.log this to see
what it looks like. console.log
and let's save our code
and we'll go back to our website
and we'll give it a try. So we'll click
this text box and we're going to type
hello.
And you'll see that every time we type
or change the text, it will console.log
the text in the text box. So that is how
we get the text inside the text box
using an onchange event.
Let's go back to our code.
And now we need to save this text so we
can use it later when creating a chat
message. To save this text, we're going
to use state. In React, we should use
state to save data that changes over
time, like the text in the text box. So,
at the top of this component,
let's use the code react dot use state
and brackets.
And between the brackets, we're going to
put the initial value. In this case, the
initial value in the text box.
The text box originally starts as empty.
So let's set the value to the empty
string.
Next, use state returns an array with
two values. So at the front, let's use
array dstructuring using const and we'll
type square brackets equals this result.
And now to get the first value out of
this array inside the square brackets
we're going to type input text.
So this is the current data or the
current text in the text box. So that's
why we name it input text.
To get the second value out of this
array after this we can type comma and
give a name for the second value. So the
naming convention is to use the word set
and then the name of the data which is
capital I input capital T text.
So this second value is an updator
function. It lets us update the data.
Now that we set up the state, every time
we change the text, we're going to save
it up here inside input text. To do
that, instead of console.log,
we're going to use the updater function
set input text.
And now, every time we change the text,
it's going to run this function. And
it's going to save the text inside input
text.
Next, when we click the send button, we
want to use this text to create a new
chat message. First, we need to make the
send button interactive.
To do that, inside this button element,
we're going to add the prop on click
equals curly brackets.
Again, on click lets us run a function
when we click this button.
And now above this, let's create a
function to run. We'll use function
and let's name it send message brackets
and curly brackets and we're going to
give this function to on click. So down
here we'll give the function name send
message.
Now when we click this button it will
run this function and let's just
console.log input text to see what the
value is. So in here we'll console.log
brackets the input text and save.
And we'll go back to our website
and in the text box we're going to type
hello and then press send.
And you'll see that it console.logs the
text inside the text box.
Next, we're going to create a new chat
message using this text. Let's go back
to our code.
And if we scroll down in our code
to the chat messages component, we
already have code here that adds a new
message to chat messages. So, let's just
select this code and we'll copy.
And at the top
inside send message, we're going to
paste. And we can remove this
console.log.
And we'll scroll back down.
And we created this function and this
button for practice. But now we don't
need it anymore. So we can actually
remove this code
and remove this practice button.
Now, let's scroll back up
and we're going to use this code to add
a new chat message.
However, we have a problem here. We
don't actually have access to set chat
messages inside this component because
this is inside a different component. To
solve this problem, we're going to learn
a technique called lifting the state up.
First we need to visualize the
components in our app. So we have an app
component which represents the entire
application and inside we have a chat
input component and a chat messages
component. Inside the chat messages
component we have some chat message
components.
This is called the component tree
because it looks like the branch of a
tree and this helps us visualize the
structure of the components in our app.
Currently, chat messages and set chat
messages are located inside the chat
messages component, but we want to use
it in the chat input component as well.
To solve this problem, we're going to
move this state up into the app
component and then app can share chat
messages and set chat messages between
these two components.
This technique is called lifting the
state up. By moving the state up to an
outer component, it lets us share state
between multiple components.
So, let's give this a try. First, we're
going to move the chat messages state up
into app. So, in our code, we're going
to scroll down
to the chat messages state, which is
right here, and we're going to move it
into the app component. So, we'll select
all this code,
and then cut
and remove these lines.
And then inside the app component,
we'll create some new lines and paste.
So now we lifted the state up into the
app component.
Next, we're going to share the state
between the two components using props.
So first, the chat input component needs
set chat messages and chat messages.
So down here, let's create two props for
this component.
We'll create a prop called chat messages
equals curly brackets. And we're going
to save the value of chat messages from
the state. So we'll save chat messages.
And we'll give it another prop called
set chat messages equals curly brackets.
And we'll give it the set chat messages
function from the state.
So set chat messages.
By the way, notice that chat messages is
an array. So using curly brackets, we
can save an array into this prop. So we
can save any type of value inside a
prop.
And then inside chat input, we can
access these two props by scrolling up.
And in the chat input component at the
top, we'll type curly brackets and we'll
get the chat messages prop,
and we'll also get the set chat messages
prop.
And now this code has access to set chat
messages and chat messages.
Next, let's scroll back down
to the chat messages component.
So here we just need the chat messages
array to generate the HTML. So let's
provide chat messages using a prop at
the bottom
at the chat messages component. We're
going to add a prop. chat messages
equals curly brackets and we'll give it
the chat messages array. So here chat
messages.
Now I want to talk about the naming
convention used here. You'll notice that
the component, the prop and the data all
use the same name. Instead of using
names like this,
this is the naming convention used in
the React documentation.
The documentation tries to use the same
name for many things like the component,
the props, and the data. This keeps
things simple and consistent. We don't
have to come up with different names
every time. And when we look at other
people's React code, the names will be
the same.
So, don't worry. It might be a bit
confusing at first because many things
use the same name. The more you work
with React, the more you'll get used to
this naming convention, and we'll get
lots of practice in this course.
Now to access this prop, we're going to
scroll up
and up here we'll type curly bracket
and we'll get the chat messages prop.
And now this code has access to
everything that it needs. Let's save our
code and then check our website.
And you'll notice that everything still
works. We just lifted the state up into
the app component and shared it between
chat input and chat messages.
Let's go back to our code
and we're going to scroll up to the chat
input component.
So now that chat input has access to set
chat messages, let's use it to create a
new chat message. So when we click send,
we're going to run set chat messages and
we're going to give it a copy of the
chat messages array with a new message
at the end. In this new message, instead
of test every time, we're going to use
the text inside the text box, which is
saved in input text. So, we'll remove
this and replace it with input text.
The sender will be the user because we
sent this message. And we'll give the
message a unique ID. And that's it. This
will update the chat messages array with
this new message. And because we use the
updater function, React will also update
the HTML.
So, let's save.
And we'll go to our project.
Inside this text box, let's type hello
and press send.
It will take the text in the text box,
create a new chat message, and it will
update the HTML.
Next, there is one improvement that we
can make at this point. If we scroll up
after we press send, we should also
remove the text in the text box. So, we
don't have to manually remove it if we
want to send another message.
To do that, we're going to learn a
feature called controlled inputs.
Let's go back to our code.
And after adding a new message, we're
going to remove the text in the text
box. So after this, let's use the
updater function. Set input text
brackets
will change the input text to the empty
string.
So this will update the input text up
here to be empty.
However, it will not update the HTML
yet.
To update the HTML, we need to use this
input text inside this HTML.
To do that, we're going to give the
input element a prop called value equals
curly brackets.
So value lets us change the value of
this input or the text inside this
input.
So we're going to set the value to
whatever input text is.
So now if we set the input text to be
empty, this will set the value to be
empty as well and it will make the text
box empty.
Let's save.
We'll go back to our website.
Inside the text box, we're going to type
hello and press send.
And you'll notice that it makes the text
box empty after we send. So let's go
back to our code.
And this is called a controlled input.
Using the value prop, we can control the
text inside this text box using our
code.
The last feature we're going to work on
in this lesson is if we scroll up after
we send a message, we're going to get a
response from the chatbot.
To get a response, we're going to use
another external library. So, we'll
scroll up to the script elements up
here. And to add another external
library, we're going to add another
script element.
And we're going to give this element the
source attribute equals double quotes.
And we're going to give it the URL of
the external library. Now, this is
another external library that I wrote.
So, let's just copy one of these URLs up
here with super simple dev. And we'll
copy.
And inside here, we're going to paste.
And then at the end, instead of
react.js,
we're going to load chatbot.js
and save.
So now, let's take a look at the code in
this URL.
On Windows, you can press control and
click this link. And on Mac, you can
press command and click this link.
If it doesn't open, you can also type
the URL in the browser.
So again, an external library is just
normal JavaScript code that someone else
wrote. In this case, it's some code that
I wrote. And this JavaScript code
creates a simple chatbot.
This is an object and it has a method
called get response.
We just have to give it our message and
it will return a response.
So now let's use this external library.
We'll go back to VS Code
and we'll scroll down to chat input. And
now after we send a message below this,
let's use the chatbot external library
to get a response. So the external
library creates a variable called
capital C chatbot.
This is an object and it has a method
called dot get response and brackets.
Between the brackets, we're just going
to put the message that we sent, which
is input text. So in here, we'll type
input text
and get response will return a response.
So let's save it in a variable using
const and we'll name it response.
equals this result. And next, let's just
console.log the response to see what it
looks like. console.log
the response
and save.
And now let's go to our website
and we're going to close the external
library for now. And then we're going to
click this text box and we'll type the
message hello and press send.
And now inside our console it will
display the response from the chatbot.
And the chatbot responded with hello how
can I help you? So using the chatbot
external library we're able to get a
response from the chatbot.
The last step is we're going to display
this chatbot response on the website.
Let's go back to VS Code.
And to display the response on the
website, we can just add another chat
message using set chat messages.
Because this is an updater function from
the state, React will automatically
update the website as well. So down here
we'll remove console.log
and let's just copy paste this code up
here to create a new message. So we'll
copy and then down here we'll paste
and here the message should be the
response from the chatbot. So we'll
replace this with response
and the sender is going to be the robot
this time. and we'll give it a unique
ID.
So now let's save this code and try it
out. We'll open the website and then in
the text box we'll type hello and press
send.
And if we look at the website, it sort
of worked. It displayed the response
from the chatbot on the website.
However, it also removed our hello
message. So why did this happen? Let's
go back to VS Code.
And if we look at this code
here, we updated chat messages by making
a copy and adding a new message at the
end. However, in React, state does not
update immediately. The state is updated
after all of the code is finished.
So here all of the code is not finished
yet. So chat messages is not updated to
this new array immediately.
So when we get to this point in the
code, this chat messages is still the
old array without the new message that
we added up here. And then we take the
old array and we add the chatbots
response. And we essentially lost our
message.
So one way to fix this issue is to save
this updated chat messages in a
variable. So above this we're going to
create a new variable using const and
let's name it new chat messages
equals
and we're going to save this value. So,
we'll select this code
and then cut.
And up here, we're going to paste.
And we'll set the chat messages to this
variable, new chat messages.
So, this does the same thing as before,
except we saved the new chat messages in
this variable.
And then down here, instead of making a
copy of chat messages, we're going to
make a copy of new chat messages, which
contains our new message that we just
added. So now it will have our message,
and we're going to add the chatbots
response. So now let's save this code
and go to our website.
In the text box, we're going to type
hello and press send.
And it displays our message, hello, and
the chatbot's response, hello, how can I
help you?
Let's try another example. In the text
box, we can type, "Can you flip a coin?"
and press send.
It will add and display our message and
it will add and display the chatbot's
response which is sure you got heads or
tails and everything is working
correctly.
So as you can see state is another way
that React helps us create websites
easier. All we have to do is update the
state and React will automatically
update the website. We don't have to
update the website manually ourselves.
And that's it. Using state, we created
the functionality that we need for this
project. In the next lesson, we'll style
this with CSS to make it look like the
final chatbot project.
And that's the end of this lesson. In
this lesson, we saved the data for our
website using arrays and objects. We
generated the HTML using map and the key
prop. We made the website interactive
using on click and onchange. We learned
state which is data that changes over
time and is connected to the HTML. We
used the updater function to update the
state and update the HTML at the same
time. We learned the array destructuring
shortcut. We learned a technique called
lifting the state up which lets us share
state between components. We made the
chat input component interactive and
created new chat messages. And we got
responses from the chatbot.
Here
are some exercises to help you practice
what we learned in this lesson.
In this lesson, we're going to learn how
to use CSS with React and we'll finish
the chatbot project. Let's go back to
our code
and we'll start by reviewing CSS.
CSS is another language and it lets us
change the appearance of the website. To
use CSS with React, we just use CSS
normally. So, one way to use CSS is to
create a style element.
So, we'll scroll to the top of our code
to the head element and then inside
here, we'll create a style element.
So, the style element doesn't appear on
the website. That's why we put it in the
head section.
And the special thing about the style
element is we can write CSS code inside.
In here we'll type the CSS code button
and curly brackets. And inside we'll
type background dash color
green and semicolon.
So this is some CSS code. As a review,
this code at the front is called the CSS
selector. This tells a computer which
elements we want to change the
appearance. And inside we have CSS
styles. This tells a computer how to
change the appearance of these elements.
The left side is called the CSS
property. This is what we're changing.
And the right side is called the CSS
value. This is what we're changing the
property to. So this code changes all
buttons on the website and changes their
background color to green. If we save
and then check our website,
you can see that it changed the
background color of the button to green.
Let's go back to our code.
And one problem here is button will
style all buttons on the website. But
usually we want to just style a specific
button. For example, let's scroll down
to the chat input component and we're
going to scroll down to this send button
here. So let's say we just want to style
this send button. As a review to style a
specific element, we can add an HTML
attribute called class. In React to set
the class attribute, we're going to give
this element a prop called class capital
N name equals double quotes.
And we'll give it the class send dash
button.
In React, we use class name to set the
class. That's because React is actually
just JavaScript code and JavaScript
already has a feature called class. So
class is a reserved word and we can't
use it. That's why React uses class name
to set the class.
Now that this button has the class
send-button,
we can style this specific element.
We'll go to our CSS
and in here we're going to remove button
and we're going to type dot and then the
class send dash button.
As a review, if we start the CSS
selector with a dot, it will only style
elements with this class. So this will
only style elements with the class
send-ash button. If we save
and check our website,
it styles our send button because we
gave it the send-button class.
If we open the console and go to the
elements tab and then we look at our
HTML here and we find the send button,
you'll notice that it has the class
attribute. So class name in React is
converted to class in HTML.
Now that we reviewed CSS, we're going to
style this button to look like the final
design. So, first we're going to put the
final design and our website side by
side so it's easier to compare. So, I'll
take the final design here and I'll put
it on the bottom left and I'll take our
website and put it in the top left. And
I'm going to resize our code editor
so we can see everything side by side.
And I'll hide the sidebar.
Next, to style our send button to look
like the final project, we just have to
style it one by one with CSS. So, we
already made the background color green.
Next, let's make the text color white.
To do that, we'll type the CSS property
color colon and set it to white and
save.
And that will make the text color white.
Next, let's make our button bigger. To
do that, we'll add space on the inside
of the button. As a review, space on the
inside of an element is called padding.
So in our CSS we're going to add padding
colon and we'll give the padding two
values 12 px and 20 px.
So the px here stands for pixels. A
pixel is a unit of measurement in
computers. For example, my computer
screen is about 3,800 pixels wide. So 12
pixels and 20 pixels looks like this.
The first value is the vertical space
inside this button. And the second value
is the horizontal space inside this
button. So we're going to add space all
around the inside of this button. So
let's save.
And it adds space on the inside.
And I think that looks close enough.
Next, let's add some space on the
outside of this button on the left. As a
review, space on the outside of an
element is called margin.
So, in our CSS, we'll add margin dash
and we'll add it on the left colon. And
let's add 10 pixels of margin. And save.
And that looks close enough.
Next, our button has a border around the
button, but in the final design, there
is no border. To remove the borders,
we'll type the property border colon and
set it to none and save.
And that will remove the borders.
Next, the corners of the button in the
final design are round. To make our
corners round, we're going to use the
CSS property border dash radius colon
and then how round we want the corners
to be. Let's try 10 pixels and save.
And I think that looks close enough.
Next, the text in the button is a little
bigger in the final design. To change
the size of the text, we'll use the CSS
property font dash size colon and let's
try 15 pixels and save.
And that looks pretty good. Next, if we
put our mouse over our button, we no
longer have the hand pointer icon that
we see here. to use this hand pointer
icon. We're going to set the property
cursor colon pointer
and save.
And now if we put our mouse over the
button, we have the hand pointer icon
again.
Finally, the background color of our
button is a little different from the
final design. So to get this exact green
color, we can go to the final project.
And then we're going to rightclick this
button and then click inspect.
And we can click these three dots here
and click this icon to open the console
in a different window.
And we're going to go to the elements
tab and we'll find the send button in
the HTML. And we're going to look at
these styles. So you can see that this
button here has a background color of
this RGB value. So we're going to select
this RGB value and we're going to copy
it.
And in our code, instead of the color
green, we're going to paste this RGB
color.
As a review, RGB stands for red, green,
blue, and it's a way to measure color in
computers. Computers can create any
color using a combination of red, green,
and blue. The first value here is how
much red we want in the color. The
second value is how much green we want
in the color. And the third value is how
much blue we want. And each value goes
from 0 to 255.
So this color combines a little bit of
red, a lot of green, and a bit of blue
to get this exact green color. So let's
save our code.
And now our button matches the final
project.
And that's how we style the send button.
We just style it one by one using CSS
until it looks like the final design. So
this is just a review of CSS. If you
want to learn CSS in more detail, you
can check out my HTML and CSS full
course in the video description.
Next, we're going to style this text box
to look like the final design. Again,
we're just going to style it one by one
with CSS.
First, we need to add a class to this
element so we can select it in our CSS.
We'll go to our code and we're going to
scroll down to this text box which is
inside the chat input component and it's
this input element here. So to add a
class we're going to use class name. So
inside the input element we'll add a
class name equals double quotes and
let's give it the class chat dash input.
Now, let's scroll back up to the CSS.
And below these styles,
we're going to type dot to select a
class. And we're going to select the
class we just added, which is chat dash
input and curly brackets. And now we're
ready to style the text box.
The first thing we'll change is there's
a lot of space on the inside of this
text box in the final design. So again,
space on the inside of an element is
called padding.
In our CSS, we'll add padding colon. And
let's do 12 pixels for the vertical
space and 15 pixels for the horizontal
space. Now let's save.
And that adds space on the inside of our
text box. And I think that looks close
enough. Next, we'll make the corners
round. To do that, we'll use border dash
radius colon. And let's try 10 pixels
and save.
And that looks pretty good. Next, our
border is too thick compared to the
final design. To change the thickness of
the border, we'll use border dash width
colon. And let's change it to 1 pixel
and save.
So that looks pretty good. Finally, the
text is bigger in the final design. To
change the size of the text, we can use
font dash size colon. And let's use 15
pixels again. So 15px
and save.
And I think that looks good enough for
now. So we styled the text box one by
one to look like the final design.
Next in the final design, the text box
is wider. And this text box is also
flexible. That means if we resize the
browser, the text box will also resize.
To make our text box flexible, we're
going to review a feature of CSS called
flexbox.
Flexbox lets us create a flexible
layout. Layout means how the elements
are positioned on the website.
Here we have a horizontal layout where
the elements are beside each other. And
also this element is flexible. So
flexbox helps us create this flexible
layout. To use flexbox we need to do
three steps. The first step is to create
a container around the elements that we
want to position. So let's go back to
our code and we're going to scroll down
to the chat input component and we'll
scroll down to the HTML.
So here we want to position the text box
and the button. So we need to create a
container around these two elements.
Right now we have a fragment around
these two elements. However, we cannot
style a fragment with CSS since
fragments don't actually appear on the
website.
Instead, we're going to switch this
container to a div element because we
can style a div element. So, inside
here, we'll type div and at the end,
we'll do slash div to convert this
container to a div element.
And now we have a container around the
elements.
The second step is to add the property
display flex to the container.
First, let's add a class name to this
container so we can select it in our
CSS. In here, we'll type class name
equals double quotes and we'll give it
the class chat-input
dash container.
And then we'll scroll up to our CSS.
And at the end we'll type dot to select
a class and we'll select the class
chat-input
dash container and curly brackets.
And finally we'll add the property
display colon flex and that will turn
this container into a flexbox.
The third step is to use flexbox
features. Flexbox has many features we
can use to control the layout or to
control how these elements are
positioned. One feature is called flex
grow. Flex grow makes an element grow
and take up the remaining space. So here
we want this text box to grow and take
up this remaining space.
So we'll go to the styles for the chat
input or the text box
and we'll add the property flex dash
grow
1 and save.
And now the text box will grow and take
up the remaining space.
If we resize the browser, the text box
will also resize to take up the
remaining space.
So now we created the layout for the
chat input that we see in the final
design.
Next we'll create the layout for the
overall app. Notice in the final project
if we resize the browser and make it
wider the app is limited to a certain
width. So it's not going to get wider.
To create this in our project, we'll set
a maximum width for our app.
So, let's go to our code and we're going
to scroll down to the app component,
which is down here, and we'll go down to
the HTML.
And currently, the app is contained in a
fragment. And remember, we cannot style
a fragment since fragments don't
actually appear on the website.
So again, we're going to switch this to
a div element so we can style it. So in
here, we'll type div and at the bottom
we'll type /ash div. And now we can
style this.
First we'll add a class to this div
using class name equals double quotes.
And let's give it the class app dash
container.
and we'll scroll up to our CSS.
And at the bottom here,
we'll type dot to select a class. And
we'll select the class app dash
container and curly brackets.
And to set a maximum width of our app,
we can just use the property max dash
width colon. and let's try 600 pixels
and save.
So now if we resize our browser the app
will be limited to 600 pixels just like
the final design. Next in the final
design notice that the app is centered
on the website. Now there are several
ways to center an element in CSS.
One way is to use margin. So we'll go
back to our code
and in the app container, we're going to
add the property margin dash left colon
and we'll set it to auto. And we'll also
set the margin dash right colon
auto.
So this will automatically add a space
on the left and right of this element
until it is centered. So if we save our
code and check our website, you'll
notice that the entire app is now
centered on the website. And now we
created the layout for the overall app.
Next, we're going to create the layout
for the chat messages. If you don't have
any chat messages in your final project,
you can add some by typing in here and
then pressing send. So notice that the
chat messages from the user are on the
right while the chat messages from the
robot are on the left. So we're going to
create this layout. First, we need to
give class names to these chat messages
so we can style them.
So, let's resize our browser for now.
And we'll go to our code. And we're
going to scroll down
to the chat message component. And we'll
scroll down to the HTML.
And we'll give each chat message a class
name equals. And we're going to do
something different this time. We'll
type curly brackets. So here we want to
give a different class name depending on
if the sender is a user or the sender is
a robot. This will let us position the
chat messages differently on the right
or on the left. To give this a different
class name depending on the sender.
We're going to use a feature of
JavaScript called the turnary operator.
As a review, the turnary operator looks
like this. And it works like an if else
statement.
If value one is true, then the result is
value two. Else the result is value
three.
The turnary operator lets us insert an
if else statement directly in the JSX.
So using a turnary operator, we can give
a different class name depending on the
sender.
Inside here, we're going to type the if
condition. So, we'll check if the sender
is equal to the string user. And then
we'll type question mark. If the sender
is the user, we'll set the class name to
the string chat-
message dash user.
And then we'll type a colon. So, this
means else. So if the sender is not the
user, we're going to give the class name
the string chat-
message dash robot.
So again the way this code works is if
the sender is equal to user, we'll set
the class name to chat message user.
Else we'll set the class name to chat
message robot. As you can see, the
turnary operator lets us insert an if
else statement directly in the JSX. And
notice that we used curly brackets here
because we want to save the result of
this code into class name instead of
just a string.
Before we continue, we can add some new
lines to this code to make it easier to
read. So, at the beginning, we can add a
new line. And then we'll add a new line
before the question mark and press tab.
And we'll add a new line before the
colon. And we'll add a new line at the
back.
And remove some spaces so that this is
vertically aligned.
So, this makes the code a bit easier to
read. We have the if condition and then
the first value and then else the second
value. Now let's save
and we'll go to our website and let's
check the HTML. So in our console, we
can click these three dots here and then
click this icon to open the console in
another window. And we'll go to the
elements tab and we'll click this
pointer on the top left and we'll select
one of these chat messages and click it.
And if we scroll down here, you can see
that each chat message now has a class.
And messages from the user have the
class chat message user. And messages
from the robot have the class chat
message robot.
So now that we added a class to each of
these chat messages, let's style these
chat messages.
We'll go to our code and we'll scroll up
to our CSS.
And at the end, let's type a dot. And
first let's select the class chat dash
message dash user and curly brackets.
And now for chat message user we want to
position these elements the text and the
profile image on the right. To create
this flexible layout we can use flexbox.
Again
remember there are three steps to use
flexbox. First, we already have a
container around the elements. It has a
class chat message user or chat message
robot.
Next, we need to add display flex to
this container. So, for chat message
user, we'll add
display colon flex.
And now we can use flexbox features.
Another feature of flexbox is we're
going to type justify dashcontent
colon.
Justify content controls how the
elements are displayed horizontally.
If we want these elements to be
displayed on the right, we're going to
give this a value end.
So it will display these elements at the
end of this row or on the right.
So now let's save our code.
And now the chat messages from the user
are on the right. And we created the
layout for the chat messages.
Next, we're going to style the text in
the chat messages.
First, we need to add a class name to
this text so we can style it.
Let's go to our code and we're going to
scroll down to the chat message
component
and we're going to scroll to the text
which is here. So currently this text is
not inside an element. So first we're
going to put this text inside an element
so that we can style just the text.
Above this, we'll put this in a div by
typing less than div greater than and
below it less than slashd greater than.
And we'll add an indent at the front to
show that this text is inside this div.
And now let's add a class to this div so
we can style just the text. So, we'll
give this a class name equals double
quotes. And let's give it the class chat
dash message dash text.
So now let's style this with CSS. We'll
scroll up to our CSS
and at the end we'll type a dot and
we'll style the class chat dash message
dash text and curly brackets.
So the first thing we'll style is we're
going to change the background color to
this gray color. To get this exact
color, we're going to rightclick on this
text and then click inspect.
and we'll find this text in the elements
tab and we're going to go into the
styles and we'll get the background
color. So, we'll copy this RGB color
and we'll go into our code and we'll set
the background dash color colon and
we'll paste the RGB color and save.
And now we'll have the exact color in
our final design.
However, after we saved, it kind of
messed up our layout. So, the chat
message user looks okay, but the text
for chat message robot is now appearing
below the profile image and it's taking
up the entire line.
So, what happened? Remember that we just
surrounded this text in a div element.
Normally a div element takes up an
entire line by itself because a div is a
block element.
However, remember that we also made chat
message user a flexbox. When a block
element is inside a flexbox, it no
longer takes up the entire line. It only
takes up as much space as it needs to.
So that's why this div only takes up as
much space as it needs because it's
inside a flexbox.
One way to fix this layout problem is we
can make chat message robot a flexbox as
well. We'll go back to our code and
below chat message user let's type dot
and we'll style the chat- message dash
robot and curly brackets
and we'll also give it display colon
flex
so it will match the layout for the chat
message user.
Let's save.
And now because this div is inside a
flexbox, it only takes up as much space
as it needs. So now the background color
and the layout looks good. Next, the
style of text or the font is different
in the final design.
To change the font, we'll go to our code
and we'll add the property font dash
family colon And in the final project, I
use the font Ariel.
Let's save.
And now our font matches the final
design.
Now, usually we don't set the font for
just one element. We set the font for
the entire website because we want the
entire website to use the same font or
the same style of text. to set the font
for the entire website. We can style the
body element. So, we'll scroll to the
top of our CSS.
And here we'll style the body element
curly brackets and we'll set the font
dash family colon to area.
So this sets the font for all elements
inside the body, which is basically the
entire website. So now we can scroll
back down
and we can remove this style
because we're going to set the font for
the entire website instead.
Let's save.
And now we set the font for the entire
website to Ariel.
Next, let's add space on the inside of
this text, which is padding.
So, here we'll add padding
colon. And let's try 15 pixels of
vertical space and 20 pixels of
horizontal space. And save.
And that looks pretty good.
Next, we'll make the corners round.
To do that, we'll use border dash radius
colon and 10 pixels and save.
And that looks pretty good. Next, let's
add space on the outside of the text on
the right. So, we'll add margin dash
right colon and let's try 10 pixels and
save.
And that looks close enough.
And here, if we scroll down to a chat
message from the robot, we'll add some
space on the left of the text. So, in
our code, we'll add margin dash left.
And let's try 10 pixels and save.
And that looks pretty good. Finally,
let's add some space on the bottom of
the text so we can separate them. Here
we'll add margin dash bottom colon. And
let's try 20 pixels and save.
And I think that looks close enough.
However, we now have a problem here,
which is the profile image seems to be
stretching.
This happens because this container is a
flexbox. And by default, elements inside
a flexbox will stretch vertically.
So, if this text gets longer because we
added some margin, this image will
stretch.
To fix this, flexbox has another feature
called align items.
So in our CSS in chat message user,
we'll add the property align dash items
colon
and align items controls how the
elements are displayed vertically. By
default, align items is stretch. That's
why the elements stretch vertically.
Instead, we're going to change align
items to start.
This will display the elements at the
start or at the top vertically, and it
will no longer stretch. Same thing for
the chat message robot. We're going to
give it align dash items colon start and
save.
And now the elements in the flexbox will
appear at the start or at the top
vertically.
The last thing we'll style for the text
is if we go to our final project and
inside the text box we type test and
press send.
You'll notice that the response from the
chatbot has a maximum width. So in our
project, we're also going to add a
maximum width to our text. So in our
code, we'll go to the chat message text
and let's add a max dash width colon.
And let's try 300 pixels and save.
And now if we go to our text box and
type test and press send and scroll
down, the text has a maximum width and
it matches the final design.
Now we finish styling the text in the
chat messages.
Next, we'll style the profile images. So
in our code, let's scroll down to the
profile image which is inside the chat
message component
and it's these two image elements here.
Currently, we're using an attribute to
set the width of this image. However, a
best practice is to use CSS for styling
instead of attributes. So let's remove
this attribute and we'll remove it down
here as well and we'll add a class to
these profile images so that we can
style them with CSS. So here we'll add
class name equals double quotes and
we'll give it the class chat-
message dash profile.
And we'll also add this class to the
profile image for the user.
We'll give it the class name equals
double quotes
chat dash message dash profile.
So now we can style this with our CSS.
We'll scroll up to our CSS
and at the end we'll type a dot and
we'll style the class chat dash message
dash profile and curly brackets.
So previously we set the width to 50
pixels. So let's do that again using
CSS. This time we'll set the width colon
to 50 pixels.
and save.
Now, if we look at the final design,
it looks like the profile images here
are a little bit smaller than our
profile images. So, let's make this
width smaller. Let's try 45 pixels
instead.
And save.
And I think that looks close enough. And
now our profile images are the same size
as the final design.
The last thing we're going to change in
this design is we're going to move the
text box to the bottom so that it
matches the design of other popular
chatbots.
In the final project, we're going to
make this a little taller. Now, we can
move this text box to the bottom of the
page by clicking this link.
And now let's create this design in our
project.
First I'll open our project and then
move it back to the same window so that
we can see this side by side a little
easier. And to put the text box at the
bottom of the page, the first step is to
move the text box below the chat
messages. We'll go to our code and we're
going to scroll down to the app
component
which is here and we'll scroll to the
HTML and we're just going to move this
chat input below the chat messages. So
we'll select this component and we'll
cut
and below chat messages we'll paste
and save.
And now the chat input will be below the
chat messages. And that looks pretty
good. Next, we also want to put this
chat input at the bottom of the browser
here. So there are several ways to do
this in CSS. One way is to use flexbox
again. Now before we use flexbox, we're
going to make the app container stretch
to the bottom of the browser. So right
now if we click inside here and we
rightclick and inspect
and we go to the elements tab and we
scroll up and look at the app container.
Notice that the app container stops at
the chat input section. And that's
because this is all the content that we
have. So the app container only has the
height that it needs. However, we want
to stretch the app container to the
bottom of the browser so that we can put
the chat input at the bottom. To do
that, we're going to set the height of
the app container. So, we'll go back to
our code
and we'll scroll up to our CSS
and we're going to find the styles for
the app container which is right here.
And at the end, we're going to set the
height colon.
And now we want the height of the app
container to stretch to be the same as
the height of the browser here. To do
that, we're going to give this a special
value 100 VH.
So VH stands for viewport height. This
gives us the height of the browser or
the part of the page that is visible.
100 VH means 100% of the height of the
browser. So this means the app container
will be 100% of this height.
So now let's save
and we'll go to our website and we'll
open the console again by right-clicking
and inspect
and go to the elements tab and we'll
scroll up to the app container again.
And now you'll notice the app container
stretches to the bottom of the browser.
However, the app container is actually a
little too tall. So it actually
stretches below the bottom of the page.
And now we can scroll a bit here. The
reason it's a little bit too tall is
because by default the body element here
has a default margin of 8 pixels on all
sides. So the app container is the same
height as the browser, but then we add
another 8 pixels on the top and bottom.
To fix this issue, we can just remove
the default margin from the body. So,
we'll go back to our code
and scroll up to the styles for the
body. And at the end, let's remove the
margin at the top and bottom by typing
margin- top colon. And we'll set it to
zero pixels. And we'll also set the
margin dashbottom
colon to zero pixels and save.
So now after we remove the default
margin from the top and the bottom,
the app container is now exactly the
same height as the browser.
Now that the app container stretches to
the bottom of the browser, we can use a
flexbox to make the chat messages grow
and push the chat input to the bottom.
Again, there are three steps to use a
flexbox.
So here we want to position the chat
messages and the chat input. So we need
a container around these elements and we
already have a container for this which
is the app container.
The second step is to add display flex
to the container. So we'll go back to
our code and we're going to scroll to
the app container styles which is right
here and below this we'll add display
colon flex. Let's save our code.
And unfortunately, it totally messed up
our design. So what happened? By
default, flexbox positions our elements
horizontally. So it takes all the
elements inside the container and then
squeezes them into a row like we see
here.
However, this time we want to position
the elements vertically, not
horizontally.
To position the elements vertically,
we're going to use a flexbox feature
called flex direction.
So in here, we'll type flex dash
direction. colon
flex direction determines which
direction the elements are positioned.
So flex direction is row by default.
That means it positions the elements
horizontally like we see here.
Now we're going to change flex direction
to column.
So this positions the elements
vertically in a column. If we save our
code
and check the website, the elements in
the flexbox are now positioned
vertically from top to bottom.
Next, we're going to use flex grow.
Again, as a review, flex grow makes an
element grow and take up the remaining
space.
Here, we want to make the chat messages
section grow and take up all the
remaining vertical space. And this will
push the chat input down to the bottom.
To use Flex Grow, we're going to add a
class to the chat messages section.
We'll go to our code and we'll scroll
down
to the chat messages component which is
right here. And currently this component
uses a fragment. And remember, we cannot
style a fragment since fragments don't
appear on the website. So again, we're
going to switch this to a div element.
and at the end slash div so that we can
style it.
And now we'll give this div a class
using class name equals double quotes
and we'll give it the class chat dash
messages dash container.
And now let's style this class. We'll
scroll up in our CSS
and at the end here we'll type dot and
we'll style the class chat dash messages
dash container
and curly brackets
and we'll use the flexbox feature flex
dash grow
1.
So now let's save.
And this makes the chat message
container grow and take up the remaining
vertical space. And this will push the
chat input to the bottom of the browser.
So that's how we use a flexbox to
position the chat input at the bottom.
Finally, if we look at the final design,
we have some space at the top of the app
and at the bottom of the app. So let's
add that space at the top and bottom to
our website.
We'll go to our CSS
and currently the app container has a
special height of 100 VH. So let's avoid
changing this. Instead, let's add space
above the Chad messages container. So,
we'll scroll down to the chat messages
container and we'll add some space at
the top using margin dash top colon 20
pixels.
And we'll also add some space below the
chat input container. So, we'll scroll
up to the chat input container which is
right here. And we'll add space at the
bottom using margin dash bottom colon.
And let's try 60 pixels and save.
And now that looks pretty good. And now
if we look at our website and compare it
to the final design,
you can see that it looks the same as
the final design. So, we finished
styling our project to look like the
final design using CSS.
Next, we're going to make the chat
messages scrollable. In the final
project, if we have more chat messages
than we can see in the browser, we can
actually scroll to see all of the chat
messages. Now, you may need to add more
chat messages down here in order to see
this feature. So, we're going to create
this feature in our project. If we go to
our project and we add some more
messages like test and press send,
notice if we have too many messages, it
starts to push the chat input down.
To make our chat messages scrollable,
we're going to go to the CSS and we're
going to find the chat messages
container, which is right here.
And at the end we'll add a property
overflow colon scroll.
So now if the chat messages overflow or
there's too many to be displayed, it
will start to scroll instead of pushing
things down. Let's save our code
and then add another message test and
press send.
And you may need to add a few more
messages to see this feature. Now, if we
have too many messages, we're able to
scroll up and down to see all the
messages.
Now, before we continue on Windows, we
have a small problem, which is we start
to see these thick scroll bars on the
sides, which doesn't look very good. To
hide these scroll bars, we can go back
to our CSS and at the end we can use the
property scroll bar dash width colon
nut.
So now let's save.
And if we add a message test and press
send and you might need to add more
messages for your project. Now, if we
have more messages than we can see, we
can scroll and we hide the scroll bars.
So, that's how we make the chat messages
scrollable.
The last feature we're going to add to
our project is auto scrolling. For
example, if we go down here and add the
message test and press send,
notice we have to manually scroll down
to the bottom ourselves. But if we go to
the final project and at the bottom add
a message test and press send,
notice that it automatically scrolls to
the bottom of the chat messages. So,
we're going to add this autoscrolling
feature.
Let's go back to our website.
And to create autoscrolling, we're going
to learn one of the most important
features of React called hooks.
Hooks let us insert React features into
our component. And we've actually used
hooks before. React.US
state is a hook. It inserts a React
feature called state into our component
and state automatically updates the HTML
when the data changes. Now, React has
other hooks that we can use and every
hook starts with a word use.
Another hook is called use effect. Use
effect lets us run some code after the
component is created or updated.
So in our project after we add a chat
message we want to run some code to
scroll to the bottom. So this is a
perfect situation for use effect.
Inside our code we're going to scroll
down to the chat messages component
which is here.
And at the top of the component, we're
going to type the code capital R react
dot use capital E effect
and brackets.
By the way, in React, we should put our
hooks at the top of the component and
they should not be inside anything. So,
don't put a hook inside an if statement
or inside a function.
Next, we'll give use effect a function.
So, inside these brackets, we'll type a
function using brackets, arrow, and
curly brackets.
As a reminder, when we give a function
to another function, we usually use an
arrow function because it's a bit
cleaner. So, React will run this
function after the component is created
and every time the component is updated
inside here. Let's try console.log
the string updated
and save.
And now if we go to our project and we
look at the console. So we'll rightclick
inspect
and we go to the console.
You'll see that after the component is
created, it runs a function and displays
updated. And then we're going to go to
our website and we're going to add a new
message like hello and press send.
So now after the component is updated,
React runs the function again. So, as
you can see, use effect lets us run some
code after the component is created or
updated.
So, now let's go back into our code
and we'll give use effect a second
parameter. So, at the end we'll type a
comma and we'll give a second parameter
which is an array.
So, this array controls when use effect
runs. If we give it an empty array, use
effect will only run once after the
component is created.
Now, inside this array, we can also put
some data such as our chat messages. So,
we'll type chat messages.
And now, React will also run this
function every time our data changes or
every time our chat messages changes.
If we save
and we look at the console,
use effect runs after the component is
created. And now if we add a message
like hello and press send,
use effect also runs after chat messages
changes.
So now let's go back to our code.
And this is called a dependency array.
It lets us control when use effect runs.
A best practice is to give use effect a
dependency array to avoid running this
function too often.
So now we learned hooks and the use
effect hook. And now we can run some
code after the chat messages changes.
The last step is after the chat messages
changes, we want to automatically scroll
to the bottom. To scroll to the bottom,
first we need to get the HTML element
that we want to scroll into our
JavaScript.
Let's go back to our code. And inside
this function, instead of console.log,
log we need to get this div chat
messages container into our JavaScript.
Now in normal JavaScript we might use
the DOM to get this element but remember
in React we should not use the DOM
manually. Instead we should use React
features to get this element
to get this element using React. We're
going to use another hook called use
ref. So at the top of this component,
we're going to type the code capital R
react dot use capital R ref and
brackets.
Use ref lets us automatically save an
HTML element from the component.
So this code creates a ref. A ref is a
container with special React features.
One special feature is we can give this
ref or this container to React and React
can automatically save an HTML element
inside this ref or inside this
container.
So between these brackets, we're first
going to put the value null.
So this is the initial value that is
saved inside this ref or inside this
container. So the ref is going to start
out as empty. So that's why we use null.
Now let's save an HTML element inside
this ref. To do that, first we're going
to save this ref in a variable. So at
the front we'll create a variable using
const and we'll name it chat messages
ref equals this result.
And then we're going to go to the HTML
element we want to save, which is this
div, the chat messages container.
And we're going to give this element a
special prop called ref equals curly
brackets. And between the curly
brackets, we're going to give it the ref
that we created above, which is chat
messages ref.
So now React will take this HTML element
and save it inside this ref or inside
this container.
To access the HTML element saved inside
a ref, we're going to go to use effect
and we're going to type the name of the
ref, which is chat messages ref and then
current.
Now the reason we put this code in use
effect is because remember use effect
runs after the component is created. So
we need to wait for the component to be
created first and then we can access
this HTML element.
So now let's console.log this value to
see what's inside this ref. So at the
front we'll console.log log open bracket
and close bracket and save.
And we'll open the console for our
website.
And you'll see that React saved the chat
messages container inside our ref.
Now that we have the HTML element, we
need to scroll. Let's learn how to
scroll it to the bottom. Let's go back
to our code
and first we're going to save this HTML
element in a variable. So we'll remove
this and at the front we'll create a
variable const and let's name it
container
lm equals this result.
So ending the variable name with lm
tells us that this variable contains an
HTML element.
and I'll resize my code editor so we can
see more of the code.
Next, we'll create a new line. And it's
a good idea to check if this element
actually exists before we scroll it. So,
we'll check if brackets container lm.
Finally, we'll type curly brackets.
And to scroll this element to the
bottom, we can use this code container
lm dot scroll top and we'll make it
equal container lm dot scroll height.
So scroll top means how far from the top
should we scroll and scroll height gives
us the total height of the element. So,
if we set the scroll top to the total
height, it's going to scroll all the way
down to the bottom, which is exactly
what we need. So, now let's save this
code
and we'll go to our website and we'll
add a message test and press send.
It runs the use effect function because
chat messages changed and it
automatically scrolls to the bottom.
Now, depending on the height of your
browser, you might need to add a few
more messages to see this effect. So, we
can also scroll up and then add another
message like thank you
and press send.
It runs use effect again and it
automatically scrolls to the bottom. And
that's all the major features that we
need for this project. I'll leave some
extra features like removing these
default messages and creating the
loading spinner as exercises.
And that's it. We created all the
styling and features that we need and we
finished the chatbot project. In the
next lesson, we'll learn how to do a
proper React setup so we can organize
our code into different files and
folders instead of putting everything
into one HTML file. And this will help
us work on bigger React projects.
And that's the end of this lesson. In
this lesson, we learned how to use CSS
with React. We styled the chatbot
project. We reviewed flexbox which lets
us create a flexible layout. We learned
the turnary operator which lets us
insert an if else statement directly in
the JSX. We learned hooks which lets us
insert React features into our
components. We learned the use effect
hook which lets us run some code after
the component is created or updated. We
learned the use ref hook which lets us
automatically save an HTML element from
the component
and we created the auto scroll feature
for the chat messages.
Here are some exercises to help you
practice what we learned in this lesson.
In this lesson, we're going to learn how
to do a proper React setup. Right now,
all of our HTML, CSS, and JavaScript
code is combined into one HTML file,
chatbot.html.
Now, it's not good to combine all of our
code in three different languages into
one file because if we work on bigger
projects, this file might contain
thousands of lines of code, and it will
be almost impossible to manage all of
that code if we put it all in one file.
Instead, we're going to do a proper
React setup that will let us split up
this code into different files and
folders.
To create this React setup, we'll need
to use the command line. So, first let's
review the command line. We're going to
go to VS Code and I'm going to make this
full screen.
And to open the command line, we're
going to click the menu at the top and
we're going to click the terminal menu
and we're going to open a new terminal.
So here we can give an instruction or a
command to the computer. For example,
we're going to type the command mkdir.
mkdir means make directory. A directory
is another name for a folder. So make
directory creates a new folder.
Then we'll type a space and we'll give
this folder a name like test.
If we press enter,
it creates a new folder named test. So
if we open our files on the left, you'll
see that it created a new folder named
test.
If that does not work for you, you can
check the troubleshooting steps in the
description.
So on this line here we can give
instructions or commands to our computer
and that's why this is called the
command line
and a terminal basically lets us use the
command line and it also lets us view
the output of the command line up here.
So we created a new folder using this
command. Now you might be wondering why
did the folder get created here inside
our project folder. As a review, the
command line runs inside a specific
folder.
To see which folder the command line is
currently running in, we can go to the
bottom and type this command pwd or
print working directory and press enter.
And this command tells us the command
line is currently running in the
react-course folder which is our project
folder right here. That means any
commands that we give to the computer
will be done inside this folder. If we
make a directory, it will create the new
directory inside this folder like we see
here. If we give it another command like
ls or list and press enter,
it will list everything inside this
folder. So it will list everything here.
As you can see, the command line runs
inside a specific folder.
Now this folder that the command line is
running in is called the working
directory or the working folder.
The last thing we need to review about
the command line is how to change the
working directory. To do that, we're
going to go to the bottom and we're
going to type the command cd or change
directory and then press space and then
the name of the folder we want to change
to like test.
the command line will look for this
folder in the working directory which is
here and then it's going to go into this
folder. So now if we press enter and
then type print working directory and
press enter
it will tell us the command line is now
running inside the test folder.
So the command line basically went
inside this test folder and it's running
inside here. By the way, this is known
as a file path. The slash here means
that the test folder is inside the
react-course folder.
So now if we give a command like ls and
press enter,
it will list everything inside the test
folder because the command line is
running inside this test folder and it
tells us there's nothing inside the test
folder.
Finally, to get out of the test folder,
we can type cd or change directory and
then space and use the special value dot
dot. Dot dot represents the outer
folder.
If we press enter,
the command line will go out of the test
folder and back into the react-course
folder.
If we type the command pwd or print
working directory and press enter,
it will tell us the command line is
running in the react-ourse folder again.
So using cd or change directory, we can
change which folder the command line is
running in and we can basically move
around our computer. So this is just a
review of the command line.
The second thing we need for the React
setup is NodeJS.
So, we're going to review NodeJS.
First, make sure you have the correct
version of NodeJS installed. To do that,
you can click this link in the
description.
Scroll down to lesson 5 and follow the
instructions here to install the correct
version of NodeJS.
After Node.js is installed, let's go
back to VS Code. And if you just
installed Node.js, we need to restart VS
Code to make sure that Node.js is
loaded.
So, we're going to click X in the top
right of the terminal
and then close VS Code.
And then we're going to open VS Code
again.
And we're going to open our project
folder, React-Course.
and we're going to open a new terminal.
So, in the top menu, we're going to go
to the terminal section and then open a
new terminal.
Now, when we install NodeJS, it's going
to add a new command to our command line
called node.
So, the node command lets us run
JavaScript code outside of a browser.
For example, here we have a file called
react-basics.js
and inside we have some simple
JavaScript code. If you don't have this
file, feel free to pause the video and
create this file. Now we can give this
file to node and it will run the
JavaScript code in this file. So here
we'll use the node command and type
space and give it the file to run which
is react-basics.js
and press enter.
So this will run the JavaScript inside
this file and a console.logs hello. So
as you can see the node command lets us
run JavaScript code outside of our
browser.
Now when we install Node.js, it also
adds another command to our command line
called npm.
npm stands for node package manager. A
package is basically an external
library. So npm lets us install external
libraries or packages into our project.
To do that, we can use the command npm
space install
and then space and then the name of an
external library or package.
As an example, we'll install the package
super simple dev.
This is a package that I created that we
can use as an example and press enter.
On Windows, if you get an error like
this, you'll need to run this command
first
and then run npm install super simple
dev again.
If that still does not work for you, you
can check the troubleshooting steps in
the description.
Once npm install finishes, npm will
download this external library or this
package into a folder called node
modules. If we open this folder, we see
the super simple dev package and inside
this contains the code that we've been
using in the chatbot project like
react.js
and chatbot.js.
npm contains millions of packages that
we can download and use in our project
and you can search for packages on the
npm website.
So this is just a review of NodeJS and
npm.
Now that we reviewed NodeJS and npm,
we're ready to do a proper React setup.
We just learned that npm has millions of
packages available to use. Some of these
packages also add a command to our
command line. For example, there's a
package called create-vit.
If we install this package, it also adds
a command to our command line called
create-vit.
The create-vit command helps us set up a
new React project.
To use the create-v command, we need to
do two steps. Number one, we need to
install the create-vt package. And
number two, we're going to run the
create-v command in the command line.
Now, npm actually has a shortcut for
this called npx.
npx does these two steps in one step.
The x means execute.
So let's go to our command line and
let's type the command npx create-vt.
And then we'll also type the at symbol.
At means we're going to use a specific
version of the create-vit command. For
this video, we're going to use a
specific version so that you have the
same code that I do and you can follow
along.
To get the version of create-vt we're
going to use, we're going to click this
link in the description.
Go to lesson 5 and here you'll find the
version of create-vt we're going to use.
You can also find the full command here.
By the way, the version that you see in
this video might be different than the
version you see on your page. You should
always use the version that you see on
your page. I did this because it's hard
to update the video. So, this lets me
easily update the version in the future.
So, select the version on your page.
Copy.
And in our command line, we're going to
paste it after the at.
So again, this command will install the
create-vt package and then it will run
the create-vit command. The create-v
command will help us set up a new react
project.
By the way, in some tutorials, they
might use the command npm create vit.
This is just a shortcut for
npxcreate-vit.
Now let's press enter.
If it says it needs to install this
package, we can press y for yes and
press enter.
Now the create-v command will ask us
some questions. First it will ask us for
a project name. So let's name it chatbot
dash project and press enter.
And then it will ask us what technology
we want to use in our project. So we're
going to press the down arrow and select
react and press enter.
And it will ask us what other tools we
want in our project. We're going to
press down and just select JavaScript
and press enter.
and create vit will create an empty
React project at this location or this
folder right here.
Next, we're going to go into this folder
with our command line. To do that, we
can use the command cd or change
directory and give it the folder name
chatbot dash project and press enter.
If we type pwd and press enter,
it will tell us the command line is now
running inside of the chatbot project
folder. So, it's running inside of here.
The next thing we're going to do is
we're going to run the command npm
install.
Inside our chatbot project folder, we
have a special file called package.json.
So, package.json JSON contains a list of
all the packages that are needed for
this project. So, npm install is going
to install all of these packages at the
same time.
So, we'll go back to the command line
and scroll down and we'll run the
command npm install and press enter.
Now, this might take a while because
it's going to install a lot of packages.
So, we just got to wait until it
finishes.
After npm install finishes, all of the
packages here are going to be downloaded
into the node modules folder. So, if we
open this, you'll see that we have a lot
of packages here. Now, you'll notice
that there's more packages here than we
have in the package.json file, and
that's because some packages require
other packages. So, npm helps us install
everything that we need.
The last step is to run the command npm
rundev.
So, this will start up our new React
website. Let's press enter.
And now we can view this website by
opening this URL in our browser. So,
we're going to select this URL and copy
and then open our browser.
And I'm going to make it full screen so
we can see more of it. We'll create a
new tab and paste and press enter.
And now we have a new React website that
we can work with. So that's how we do a
proper React setup using the command
line npm and vit.
Now that we created a proper React
setup, let's go back to VS Code
and we'll learn what each of these files
and folders do. As a review, the node
modules folder is where npm installs all
of the packages.
Next, we're going to look at the src or
the source folder.
This folder contains the code for our
website. So, all our JavaScript and CSS
code goes in here. And remember, when
using React, we write JSX code rather
than normal JavaScript code. So, the
files here end with JSX instead of JS.
Next, this assets folder contains images
that we want to display on our website.
So, here we have an image of the React
logo in SVG format.
The last folder here is the public
folder. The public folder contains files
that should be available to the public.
Public means we can access these using a
URL. That means that when this website
is on the internet, I can give you a URL
to this image and you'll be able to
access it.
So here they just put this vit image in
the public folder as an example. So now
we understand the folders that we have
in this setup.
Next let's learn about all the files in
this react setup. The first file.get Git
ignore is used by a tool called git. Git
helps us track changes in our code. For
this chatbot project, we're not going to
use git. So this file doesn't do
anything. So we don't need to change
this file.
The next file here is eslint.config.js.
So this is used by a tool called eslint.
eslint highlights problems in our
JavaScript code. Let's do an example. If
we open the source folder and we open
the file app.jsx
and let's say that here I accidentally
misspell setc count by removing the last
t.
My VS code doesn't really tell me that
there is a problem here. But ESLint will
tell me very clearly that there is a
problem. To use ESLint, we need to
install the ESLint extension. So we can
go to the extension section
and we'll install the extension ESLint
and we'll install it.
After it's installed, if we go back to
app.jsx
now, it's going to tell me with a red
underline that this variable name does
not match the variable name down here.
So, if we scroll up and we fix the
spelling by adding back the t, that red
underline or that error will go away.
As you can see, eslint is a really
useful tool that highlights problems in
our JavaScript code. So, if we go back
to the eslint.config.js,
this file configures eslint, it tells it
what to check for. So, this
configuration file is actually good
enough for now. So, we don't need to
change this file.
The next file in our setup is index.htm.
html.
This contains all the HTML code for our
React website. So, this is the same
thing as chatbot.html.
The main difference is instead of
putting all of our code inside the HTML
file, index.html
loads our JavaScript from a different
file.
So this is the one file that we may need
to change inside this setup. If we want
to change the HTML for our website,
for example, we can change the title at
the top of the tabs by removing this
and let's change it to chatbot
project.
If we save,
vit will automatically refresh our page
just like live server does. And if we
open our website, you'll see that the
title at the top changed.
Let's go back.
So the index.html
contains the HTML code for this website.
The next file in this setup is
package-lock.json.
As a review, package.json has a list of
packages that we need to install to run
this project. What package lock.json
does is it saves the version numbers of
all the packages that we installed. So
the next time we run npm install, this
file makes sure that we get the same
versions for all of these packages.
Now npm automatically updates package
lock.json. So we don't need to change
this file. The next file in the setup is
package.json. JSON and this basically
contains the list of packages that we
need in our project as well as some
other information about our project.
When we npm install a package, it will
automatically update this list of
packages. So we don't need to change
this file.
Next, we have the file readme.md.
So this is just text. It provides more
information about this project. And this
is not code. This is just forformational
purposes. So we don't need to change
this file.
Finally, vit.config.js
configures vit. Vit is the tool that we
used to set up this project. Vit also
helps us build the website. That means
it takes all the JavaScript and CSS and
then loads them into the HTML file. Vit
also creates a server. A server puts our
website at a URL. For example, here it
put our website at the URL localhost
5173.
So this lets us view the website in a
web browser like a real website. When we
were building the chatbot project in the
previous lessons, we used an extension
called live server. Live server
automatically refreshes the website when
we change some code. The VIT server also
refreshes the website when we change
some code. So the VIT server is actually
a replacement for the live server that
we used earlier. So those are three main
features of Vit and you can see that
it's really helpful for setting up and
developing a React website. We'll go
back to VS Code.
So the vit config.js file basically
configures vit. So this config file is
good enough. So we don't need to change
this file. And that's it. Now we
understand all the files and folders in
this react setup. As you can see most of
these files are just configuration files
and we don't need to change them. The
only files we need to focus on and
change are the HTML file and the files
in the source folder which is our CSS
and JavaScript files.
Now that we understand all the files and
folders in this React setup, let's move
our previous chatbot project into this
setup. First, we can close the chatbot
project folder for now. And let's
actually remove the node modules folder
that we created earlier for practice. So
we'll delete this folder
and let's also delete the test folder
that we created for practice
and also the package lock.json and
package.json.
Next, let's go into the chatbot project
folder and we'll open the source folder
and we'll start with this file app.jsx.
So notice that in this file we have a
react component called app and this
component represents the entire
application.
Now previously in chatbot.html
we also created an app component.
So all we have to do is to replace this
app component with our previous app
component. So let's go to our code and
we're going to open chatbot.html
and we're going to scroll down till we
see the app component which is down
here. So we're going to select the app
component
and make sure you don't select the code
down here. We just want to copy the
component over. So, we're going to copy
this
and then go back to app.jsx
and we're going to remove this app
component. So, we'll select it
and remove it and we're going to paste
the app component from our previous
project.
And now we're going to scroll up and
eslint is going to tell us we have some
errors here. So we'll go through these
errors one by one.
First for this error eslint is going to
tell us that react is not defined.
Before we loaded the react external
library using a script tag and this
provided a variable called react.
However, now that we're using NodeJS,
we usually don't use script tags to load
the external libraries. Instead, we
download these packages into Node
modules and then load it from node
modules. With node modules, we can use a
JavaScript feature called modules to
only load the parts of the external
library that we need. So when using npm,
a best practice is to load external
libraries from node modules. Instead of
using a script tag
to load an external library from node
modules, we use the word import. And
then we tell the computer which external
library or which package we want to load
from by typing from and then the name of
the package like the string react. If we
just type a name directly like this and
we don't start with dot slash or slash,
this tells the computer to look inside
node modules for the React package. So,
it's going to look in here and it's
going to find the React package in here
and load it from here.
Also, when importing from node modules,
we don't have to import the entire React
library. we can just import what we
need. For example, here we just import
the use state feature from React.
So now that we imported use state, we
can just use this directly here instead
of doing react dot use state. So we can
remove react dot and use state directly.
Next, these two lines import images that
were used in the example website. So,
we're no longer using these images. So,
ESLint displays an error. To fix this,
we can just remove these imports.
Next, let's scroll down
and it's going to tell us that the
components chat messages and chat input
are missing and they don't exist in this
file. So, let's actually just copy them
over from chatbot.html.
So, we'll go back to the previous
project
and in chatbot.html, HTML. We're going
to scroll up
and above the app component, we're going
to copy over all of our other
components. So, we're going to select
all this code
and we're going to copy
and let's go back to app.jsx
and we'll scroll up above the app. We're
going to paste all of the other
components that we created.
And now if we scroll down and look at
our app component, you can see that
there's no more errors because we moved
these components into this file. So now
we've moved the app component into this
new React setup.
After copying over all of our other
components, we now have some more ESLint
errors. So, let's scroll up to the top
and we'll fix these errors one by one.
First, you might see an error here for
the props.
ESLint tells us that these props are
missing props validations.
Props validation was an older feature of
React. Newer versions of React don't use
this feature. So, we can actually turn
off this check in eslint.
To turn off a check in eslint, we're
going to go to the eslint config.js
file, and we're going to scroll down to
the rules section here. A rule tells
ESLint what to check for. At the bottom
of this object, we're going to add the
string react slprop-types
colon and we'll set it to the string off
and save.
So, this will turn off this particular
rule or this particular check. And now,
if we go back to app.jsx, jsx. We no
longer have those eslint errors because
we turned off the check.
Next, remember that we're no longer
using react.
We can just use state directly. So, we
can remove react dot.
Next, let's scroll down and eslint will
tell us that chatbot does not exist in
this file. So, previously we loaded the
chatbot using a script tag. But
remember, now that we're using npm, a
best practice is to load the chatbot
from node modules.
First, we need to download the chatbot
into node modules. To do that, we're
going to install the package super
simple dev. Let's go back to the command
line.
And currently, it's running the vit
server. So, we're going to stop the
server by pressing control C on Windows
or control C on Mac. Note that on Mac,
it's control C, not command C. So, this
will stop the V server and bring us back
to the command line. Usually, to exit
something from the command line, we can
press control C in both Windows and Mac.
Next, we're going to npm
install
the package super simple dev. So, this
package contains the chatbot code that
we were using earlier. Let's press
enter.
It's going to install the super simple
dev package inside node modules. And now
to load it from node modules, we're
going to scroll up in our code and at
the top we're going to import
and type curly brackets. So we're going
to import the chatbot object and we're
going to import it from a string and
we'll import it from the package super
simple dev. So this will load the super
simple dev package from inside node
modules and get the chatbot out of it.
And now that we have this chatbot
object, if we scroll down, we have
access to it. So it's no longer giving
us an error.
Finally, we're going to scroll down
to the chat messages component.
And here it's telling us that React does
not exist. So just like with use state,
we can import use ref and use effect
directly as well.
So let's remove the react dot from here
and remove react dot from here.
And we're going to scroll up
and at the top we're already importing
from the React package. To import
multiple things we can just add a comma
at the end. and import use ref and add
another comma and import use effect.
This gets these two features out of
React and now we can use them directly
in our code.
And now we've fixed all the ESLint
errors in our app component. If you did
the exercises in the previous lesson,
you may have some more ESLint errors.
So, make sure you fix any other errors
that you have. And finally, let's save
this file.
Next, we're going to look at the file
main.jsx.
So, this code sets up React. It calls
create root, gives it a container, and
then renders the app component onto the
website. If we open our chatbot.html
HTML and we scroll to the very bottom.
You notice that we do the same thing. We
call create root, give it a container,
and then render the app onto the
website. So main.jsx
does the same thing as this code. It
sets up React and displays the app onto
the website.
Now, instead of copying this code over
to main.j jsx. We're just going to use
the code in this file because it
basically does the same thing. It just
uses an ID for the container instead of
a class. The one other difference in
this code is it wraps the app in a
component called strict mode. Strict
mode is a special component provided by
React. Strict mode basically gives us
some additional checks and warnings when
developing our app.
And that's it. We moved all of our
JavaScript code into this new setup.
Now, let's open this app in our browser
to see what it looks like. We'll go down
to the command line and let's make sure
we're running inside the chatbot project
folder by typing pwd and press enter.
So, that looks good. And we're going to
start the VIT server by typing npm
rundev
and press enter.
And we'll open this URL in our browser.
I already have it open.
So I'll open my browser and refresh this
page. And now the website displays our
previous chatbot app. in the text box.
If we type a message like hello and
press send,
it will display a response from the
chatbot.
However, obviously it doesn't look
right, and that's because we haven't
moved our CSS code and images over into
the new setup. So, we're going to do
that next.
Let's move our CSS code into this new
React setup.
We'll go back to VS Code
and we're going to open chatbot.html
and we're going to go to the top of this
file right here.
So at the top we have all of our CSS
code. We're going to move this CSS code
into app.css.
So, we'll select all of this CSS
all the way to the bottom and we're
going to copy it
and then open app.css
and we're going to remove this default
CSS. So, we'll remove this and then
paste our CSS code and save.
And now how does this CSS code get
loaded on the website? If we open
app.jsx,
notice at the top we import/app.css.
So dot slash means the current folder.
It means the folder that contains this
file, which is the source folder. So
it's going to start from source and look
for a file called app.css.
and it finds it here and it will load
all the CSS code in this file onto the
website. So you might be wondering how
can we import a CSS file like this?
Doesn't import only work for JavaScript
files. So this is actually a feature of
Vit. Vit lets us import any type of file
like a CSS file or even an image file.
Depending on the type of file, it will
behave differently. If we import a CSS
file, vit will load all the CSS code in
this file and apply it to the website.
So that's how this works. We use Vit to
load the CSS code inside app.css CSS.
And this allows us to separate our CSS
code into its own file to make our code
more organized.
Next, you'll also notice that in here we
have an index.css
file.
This CSS file is loaded by main.jsx
here using this import. So why do we
have two CSS files? A best practice is
to split up our CSS into different
files. All the CSS for the app component
go inside the app.css file. All the CSS
for the overall website should go inside
index.css.
If we open app.css
and we scroll to the top,
the body styles here are not related to
the app component. This styles the
overall website. So a best practice is
to split up this code and move this into
index.css.
So we'll select this code and then cut
and save
and then inside index.css CSS.
We're going to remove this default code
and paste those body styles and save.
If we go back to app.css,
the rest of this code is related to the
app component. So, it makes sense to
leave it in app.css.
And now we moved all of our CSS into our
new React setup. So, let's open our
project again in the browser to see what
it looks like.
And now it's looking pretty good. It's
looking like our previous chatbot
project. And we have the layout and
styling that we need. The last thing
we're missing here are the images. So,
we're going to move those. Next,
let's move the robot image and the user
image into the new React setup. We'll go
back to VS Code
and we're going to scroll down and we're
going to select the robot.png image and
we'll copy it by pressing control C on
Windows or command C on Mac.
And let's scroll up and we're going to
put it inside the source/assets
folder. So, this is typically where we
put our images. So, let's click on this
assets folder and we're going to paste
the image by pressing controlV on
Windows or commandV on Mac.
And now we have the robot image in our
new setup. Let's do the same for the
user image. So, we'll go down and select
user.png
and we'll copy
and then select the assets folder and
we'll paste.
And now we need to load these images
into our app. Let's open app.jsx.
And to load this image, we can actually
just import it. So at the top, let's
type import
and we'll give this image a name like
robot profile image. And we'll import it
from a string. and we're going to locate
this image file. So inside here, we'll
start by typing dot slash, which means
the current folder or the folder that
contains app.jsx,
which is the source folder. So we're
going to start from the source folder
and then we're going to go into the
assets folder. So, we'll type assets.
And to go into this folder, we're going
to type a slash. And then we're going to
look for the file robot.png.
So, we'll type robot.png.
So, this is a file path. It tells the
computer how to locate this file.
So also notice that in this import we
just gave it a name instead of using
curly brackets.
This is called a default export and
we'll review this later in the lesson.
But for now just remember that when we
import an image we just give it a name
without curly brackets.
Let's also load the user image. So,
we're going to import and give it a
name, user profile image, and we'll
import it from a string. And we're going
to locate the user.png file. So, we'll
start from the current folder using dot
slash. We'll look for the assets folder
and then slash to go into this folder.
And we'll look for the file user.png.
So remember this is a feature of vit.
Vit lets us import any type of file
including an image file. When we import
an image like this, vit gives us a file
path to that image. So this contains a
file path like this. And we can use this
directly in an images source attribute.
So, let's scroll down to the chat
message component. And in here, we have
our two image elements. So, in the
source attribute, instead of robot.png,
we're going to give it those images that
we imported by typing curly brackets.
And here for the robot, we'll insert the
variable robot profile image. And we'll
do the same thing for the user. We'll
remove the source attribute
and type curly brackets. And we'll
insert the user profile image. So that's
how we import images using Vit and use
them. Now let's save
and we'll check our website.
And now all of the images are loaded.
So, let's try adding a message to make
sure this is working. We'll type the
message hello and press send.
And that's it. We finished moving our
chatbot project into this new React
setup.
We'll go back to VS Code.
And the big advantage of this setup is
we can separate our code into different
files instead of combining everything
into one file like we had before. Right
now we already separated our code a bit.
We separated the app component into
app.jsx
and we separated the code that sets up
React into main.jsx.
Now we're going to separate our code
even more. So, inside app.jsx,
if we scroll to the top,
notice that there's many other
components in this file, like the chat
input component. A best practice is to
separate each component into its own
file. This makes our code easier to work
with because each file only focuses on
one component.
So, let's separate the chat input
component into its own file.
First, we're going to go to the source
folder and we're going to create a new
folder in here to group our components
together. So, we'll click this folder
and we're going to click this icon to
create a new folder and we'll name it
components
and press enter.
And inside this components folder, we're
going to create a new file for our chat
input component. So in here, we'll click
it and then click this icon to create a
new file. And we'll give it the same
name as the component. So we'll name it
capital C chat capital I input.jsx
and press enter.
And now we're going to move the chat
input component into this file. So we'll
open app.jsx
and we'll select the code for chat input
which is down here.
And we're going to cut
and then open chatinput.jsx.
And in here we'll paste.
and we'll scroll up and we're going to
fix these eslint errors. We'll start
with this one. Use state currently
doesn't exist in this file. So, we need
to import it again.
Let's go back to app.jsx.
And at the top, let's copy this import.
So, we'll select it and copy.
And we'll go to the chat input file. And
at the top of this,
we're going to paste the import.
Now that we imported the use state,
we're able to use it and there's no
longer an error. Now, eslint also tells
us that we're not using use ref or use
effect in this file. So, we can remove
these.
Next, we're going to scroll down in this
file and we'll see that the chatbot
object doesn't exist anymore in this
file. So again, we'll go back to app.jsx
and let's move this import. So we'll
select it and chatbot is not used
anymore in this file. So this time we're
going to cut
and inside chat input at the top we're
going to paste that input.
And now we have access to the chatbot.
The last error here is that the chat
input component is not being used. To
fix this, we need to review a feature of
JavaScript called modules.
By default, any variables or functions
that we create in a file only exist in
that file. So chat input only exists in
this file. It cannot be used outside
this file. This helps us avoid naming
conflicts because if we use the same
variable name in different files, it
won't cause an error. Now, if we want to
use this variable outside of this file,
we need to export it first. To do that
in front of this function, we can just
type export.
And now this error is gone because
ESLint assumes that we're going to use
this component outside of this file. So
now let's save.
And to use chat input in another file,
we need to import it. So we'll open
app.jsx.
And at the top, we're going to import
and type curly brackets. And in here,
we'll import the chat input component.
And we'll import it from a string. And
we're going to locate the chat input
file.
At the front, we'll type dot slash to
start in the current folder, which is
the source folder. And then we're going
to go to the components folder.
And we'll type a slash to go into this
folder. And we'll locate the file chat
input.jsx.
By the way, when importing a JavaScript
file or a JSX file, if we're using Vit,
we don't have to add.js or JSX at the
end. Vit will actually add this
automatically. So, as a shortcut, we can
remove this.
Also, a common practice is to import
from packages at the top and then
JavaScript files and then other types of
files. So now we learn how to create
these imports ourselves using the
JavaScript modules feature and the word
export. And we can use chat input in
this file.
Next, let's move the rest of these
components into separate files. First,
we'll move the chat message component.
In the components folder, we'll click it
and we'll click this icon to create a
new file.
And let's name it the same as the
component. Capital C chat, capital M
message.jsx,
and press enter.
And now we're going to move the code
over. So we'll open app.jsx JSX and
we'll select this component
and cut.
And then inside chat message.jsx,
we're going to paste the component.
And again, we'll scroll up and fix the
ESLint errors. So, first it's telling us
we're not using this component in this
file. To fix this at the front, we're
going to export this component so it can
be used in other files.
If we scroll down, ESLint tells us that
these images are missing. So, we need to
move those imports into this file. We'll
go back to app.jsx JSX
and at the top we're going to select
these two image imports and we're going
to cut
and inside chat message.jsx
we're going to scroll to the top
and paste.
Now one thing we need to be careful
about is that we may need to update
these file paths. So now this file is
inside the components folder. That means
dot slash is going to start at the
components folder. It's not going to be
able to find the assets folder anymore.
To fix this at the front, we're going to
use dot dot slash.
So just like in the command line, dot
dot represents the outer folder. This
means it's going to go out of this
components folder and into the source
folder. And then it's going to look for
the assets folder. It's going to find it
and it will go into the assets folder
and find robot.png.
And we need to make the same change for
the user image. At the front, we'll use
dot dot to go out of the components
folder into source. And then we can
locate the assets folder.
And now these imports will work
correctly. And we finished moving the
chat message component into its own
file.
Let's save.
And we'll go back to app.jsx.
And we'll move the chat messages
component into its own file. Inside the
components folder, we'll click it. We'll
click this icon to create a new file.
And let's name it the same as the
component capital C chat capital M
messages.jsx
and press enter.
We'll go back to app.jsx JSX and we'll
select the code for this component which
is till here and we're going to cut.
And inside chat messages we're going to
paste.
Let's scroll to the top.
And this component needs use ref and use
effect. So let's move those imports into
this file. We'll go to app.jsx.
We'll select this import at the top
and copy.
And in chat messages
at the top,
we're going to paste that input.
And in this component, we do not use use
state. So we can remove it.
Let's scroll down. And in this
component, we also use the chat message
component. So let's import that. We'll
scroll up and at the top, we'll import
curly brackets the chat message
component from a string
and we'll locate this file using dot
slash. So it starts in the current
folder which is the components folder
and we'll look for the file chat message
and remember we don't have to add JSX at
the end. Vit can automatically add it.
Finally eslint tells us this component
is not used in this file. So we need to
export it. However we're going to do
something different this time.
Instead of typing export at the front of
this function, we're going to scroll
down to the bottom and at the end, we're
going to type export default
and then what we want to export, which
is the chat messages component.
As a review, this is called a default
export. It's useful if we want to export
one thing from a file. So now let's
save.
And to import this, we're going to go to
app.jsx.
And at the top, we're going to import.
And for a default export, we can just
type a name without curly brackets. So
we can type chat messages.
We'll import it from a string
and we'll type dot slash to start in the
current folder. So for this file, we're
in the source folder and then we're
going to go into the components folder
components slash and locate chat
messages.
So this imports whatever the default
export is from this file and names it
chat messages. This feature is called a
default export. When we import and we
use curly brackets like up here, this is
called a named export.
So some people like using default
exports because it encourages each file
to focus on one thing. However, it's up
to you which style of export you want to
use. You'll also find that some packages
use named exports while other packages
use default exports.
So, this is just a review of JavaScript
modules. If you want to learn about
modules in more detail, you can check
out my JavaScript full course in the
video description.
Next, let's fix these last few errors.
So we're not using use ref or use effect
in this file anymore. So we can remove
these.
And finally, this app component is
already in a file called app.jsx.
So we can just leave it in this file.
And usually we put the app component
outside of the components folder because
app represents the entire application.
It's sort of the most outer component of
our application. So it makes sense to
put it in the outer folder.
So now let's save this file.
And let's make sure that all these other
files are saved. And now we'll open our
website in the browser and try it out.
And it looks pretty good. Let's refresh
just to be safe. And we'll give it a
try. We'll click this text box and type
the message hello and press send.
So, it's working correctly just like
before. So, we'll go back and now we
separated each component into its own
file. And this makes our code easier to
work with because each file only focuses
on one component and each file contains
less code.
The last thing we're going to do in this
lesson is to separate the CSS into
different files. So, let's open app.css.
And you'll notice that in here it
contains CSS for multiple components.
So, we're also going to separate the CSS
so that each component has its own CSS
file.
For example, this CSS code is related to
the chat input component. So, we'll go
to the components folder and click it.
And we'll click up here to create a new
file. And we're going to name it the
same as the component, capital C, chat,
capital I input
CSS, and press enter.
and we'll move all the CSS related to
the chat input component in here. So in
app.css,
we'll select this code for the send
button, the chat input, and the chat
input container.
And we'll cut
and chat input.css,
we're going to paste that code
and save.
And now to load this CSS code, we're
going to open chatinput.jsx.
And at the top, we're going to import a
string
and the CSS file we want to load, which
is this one. So we'll type dot slash to
start in the current folder, which is
components, and we'll load chat
input.css.
and save.
As a review, this is a feature of Vit.
If we import a CSS file, it will load
all the CSS in the file and apply it to
the website.
Next, let's go back to app.css.
And these styles are for the app
component. So, it actually makes sense
to leave them inside the app.css file.
Below this, these styles are for the
chat message component. So, let's create
a CSS file for the chat message
component. We'll go into the components
folder and click here to create a new
file. And we'll name this chat
message.css
and press enter.
And we'll go back to app.css CSS and
we're going to select the styles for the
chat message user, the chat message
robot, the text, as well as the chat
message profile
and cut.
And then inside chat message.css,
we're going to paste the CSS code and
save.
And we're going to load this by going
into chat message.jsx JSX and at the top
we're going to import a string and we'll
import this file using dot slash
chat message
CSS and save.
We'll go back to app.css.
Finally, these styles are for the chat
messages component.
First, we'll create a CSS file for this
component. So, we'll click this folder
and click here to create a new file and
we'll name it chat messages.css
and press enter.
And in app.css,
we're going to select this code and cut.
And in chat messages.css, CSS. We're
going to paste
and save.
And we'll load this by opening chat
messages.jsx.
And at the top, we will import a string.
And we'll locate the file dot slash chat
messages.css
and save.
And finally, we'll go back to app.css
and make sure that we save all of our
files.
Now, let's open our website in the
browser.
And everything should look and work
correctly.
Let's go back to our code.
And that's it. We split up our
JavaScript and our CSS code into
separate files. And now each component
has its own JavaScript file and its own
CSS file. This makes our code a lot
easier to work with because each file is
focused on only one component and each
file contains less code.
In the next lesson, we'll use this new
React setup to work on a bigger React
project, which is an ecommerce website
that has multiple pages and more
advanced features. And that's the end of
this lesson. In this lesson, we created
a proper React setup using the command
line, npm, and vit. We reviewed the
command line, which lets us give
commands to our computer. We reviewed
npm which helps us download and use
external libraries or packages. We
learned the create vit package which
helps us create a proper React setup. We
moved our chatbot project into the new
React setup. We learned how to use
eslint which highlights problems in our
JavaScript code. We reviewed JavaScript
modules which lets us separate our code
into different files. And we separated
each component in the chatbot project
into its own JavaScript and CSS files.
Thanks for watching so far. If you find
this course valuable, you can support
the channel by liking this video,
leaving a comment, and subscribing.
You can also check out the premium
version of this course where you'll get
all the lessons ads free broken down
into small videos as well as additional
lessons and more projects that are not
in the public react course. Currently,
the premium course contains 11 lessons
and I'll be adding more lessons in the
future. You can also get a certificate
of completion, create comments or
questions on specific topics, get
progress tracking, search and course
notes. You can also check out the
membership where you can get this course
ads free separated by each lesson, AI
videos, backend tutorials, and more.
Thanks again, and let's continue with
the course. Here are some exercises to
help you practice what we learned in
this lesson.
In this lesson, we're going to start a
bigger project using React and we'll
learn an important feature called
routing.
By the way, if something in this lesson
does not work for you, you can check the
troubleshooting guide in the
description.
First, let's take a look at the project
we're going to build. In our browser,
we're going to create a new tab.
And at the top, we're going to go to
supersimple.dev/proscommerce.
And we can close these other tabs.
This is an e-commerce project or an
online shopping project. We can add
products to our cart.
And then we can click here to view our
cart.
And this page will display all the
products in our cart. It will calculate
the total for our order. and it will
also calculate a delivery date. And then
we can create an order.
And this page will list all of the
orders that we created. We can also
click this button to track the order. So
depending on the delivery date, it will
show you the progress of the delivery.
And we'll click here to go back to the
orders page.
So notice that this project has multiple
pages. So, it's much bigger than the
chatbot project. And we're working with
more data than before. So, we have
products, we have a cart, and we have
orders.
By the way, if you ever need to reset
the cart or the orders, you can click
this reset button here in the bottom
right, and it will reset everything back
to the default data. So, let's click the
top left to go back to the main page.
And now that we introduced the project,
we're going to build this with React.
We'll go back to VS Code
and we'll collapse the chatbot project
folder.
And before we create a new React
project, let's group these older files
into a folder. We'll click this HTML
file and we'll create a folder. And
let's name it React-basics.
and we're going to move all these files
into this folder. Now, a shortcut here
is to click this file and then press
shift on your keyboard and click the
bottom file and it will select all the
files between those two and we can drag
this into the folder
and we'll collapse it. So, that just
helps us stay a little more organized.
Next, we're going to set up a new React
project using VIT. To do that, we're
going to go to our terminal.
If you have the VIT server running, you
can close it by pressing Ctrl + C on
Windows or control C on Mac.
So, if you're continuing from the
previous lesson, the terminal should be
running inside the chatbot project
folder. To confirm that, we can run
print working directory or pwd.
And it will tell us that we're inside
the chatbot project folder. Now, to set
up a new React project, we want to be
inside the React-Course folder. So, to
get out of the chatbot project folder,
we can run the command cd dot dot.
And if we press pwd,
we should be inside the react-course
folder. Another way to do this is to
just start a new terminal.
Now we'll use vit again to set up a new
react project.
In the command line, we'll run the
command npx
create-ash
vit and we'll type at and give it a
version. So, you can find the version in
the description by clicking this link
and going to lesson six and you'll find
the version of vit that we're going to
use as well as the full command.
By the way, the version that you see in
this video might be different than the
version you see on your page. You should
always use the version that you see on
your page. I did this because it's hard
to update the video. So, this lets me
easily update the version in the future.
So, select the version on your page.
Copy.
So, I'm going to paste the version here
and press enter.
For the project name, let's name it
ecommerce-
project. Press enter.
And from this list, we'll press the down
arrow and select React.
And from this list, we'll press down and
select JavaScript.
And it will set up a new React project
inside our React-Course folder, which we
see right here. And now we need to go
into this folder using the command cd
ecommerce-
project.
And we're going to run npm install to
install all of the packages inside
package.json.
So we'll run npm install.
Once we have everything installed, we
can run this project using the command
npm rundev.
And now we can open this project using
this URL in the browser. So we'll select
this URL and copy.
And in the browser,
we're going to create a new tab.
And then here we'll paste.
And now we have a new React project.
Before we start updating the code, we're
actually going to review a tool called
Git. Git helps us track changes in our
code, and it's useful in bigger projects
because we're going to be making lots of
changes, and it's easy to forget what we
changed. So, Git will help us track our
changes.
We're going to go to our code
and we're going to open the Git section
here.
If you already have Git installed, it
should say initialize repository. If you
do not have Git installed, you can click
this link in the description, go to
lesson six, and follow these
instructions to install Git.
Once you have git installed, we'll click
initialize repository.
Now, a repository is just a folder where
git is tracking changes. At first, git
will tell us that all of these files or
everything inside our react-ourse folder
is new. And that's because a repository
starts out as empty. So, git considers
all of these files as new files.
We'll go back to the git section
and we'll scroll up and we're going to
save all of these files into git. At the
top, we'll type a message to describe
our changes. So, let's type the message
add the starting files and press commit.
Commit means we're going to save these
changes into git.
Now, you might run into an error when
using git and it tells you you have to
configure your username and email. To do
that, you can run these two commands in
the command line and choose your
username and choose the email you want
to use and try to commit again. And now
it should work.
If it asks to confirm, you can press
yes.
And now git will start tracking any new
changes that we make. For example, if we
go into our code and open the e-commerce
project and change some of these files,
we type test and save.
And in the source app.jsx, we type test
and save.
And then we can go to the git section.
And now git will tell us everything that
we changed in these two files. So as you
can see git helps us track changes in
our code.
Also git lets us undo our changes. So to
undo this change we can click this arrow
button here.
And to undo all of our changes at the
top we can click this arrow button here.
So, that's a review of how Git works. It
can track our changes and it lets us
easily undo our changes. Let's go back
to our files
and remember that in our React setup, we
have a file called.git
ignore. So, now we can learn what this
file does.
Git ignore tells git which files and
folders to ignore or not to track
changes. For example, in this file we
can see the folder node modules. So this
tells git that if there are any changes
inside node modules it will not be
tracked. The reason we ignore node
modules is because this folder is very
large and none of the changes inside
this folder are changes that we make.
Instead, we generate this folder using a
package.json and npm install. So,
because this folder is generated, it
doesn't make a lot of sense to save this
in git. So, that's a review of Git. Git
helps us track changes in our code and
doggit ignore tells Git which files and
folders to ignore or to not track
changes.
Now we're ready to start the project.
First, we're actually going to download
the HTML and CSS for this project. We'll
click this link in the description and
then click here.
And this will open GitHub.
And this contains all the HTML and CSS
for the e-commerce project. The reason
we're going to use some starting code is
because this course is focused on React.
By using this code, we can focus on
learning React features rather than
spending our time writing HTML and CSS.
If you want to practice HTML and CSS,
you can try to recreate the design on
your own after this course.
Another reason we're using some starting
code is in the real world, we often work
on an existing project rather than a new
project. So this will give us some
practice working on an existing project.
So to download the starting code, we're
going to click this code button here and
we'll click download zip
and we'll open our downloads folder.
For me, it's here. And we're going to
unzip this file. On Windows, we're going
to rightclick and click extract all
and extract.
And on Mac, you can just doubleclick the
zip file.
And then we're going to open this
folder.
And we're going to move all of these
files and folders into VS Code. First,
let's go into VS Code.
And we're going to organize all of those
files into a new folder. So, we'll click
the e-commerce project and create a new
folder.
And we'll name this starting dashcode.
And we'll open our downloads folder
again.
And we're going to move all of these
files into this new folder. So we'll
select it. And we're just going to drag
it into starting code.
And let's save these changes into Git.
So then Git will start tracking any new
changes that we make.
We'll open the git section and here we
added all of the starting code and at
the top let's type the message add the
starting
HTML and CSS code and commit.
Let's go back to our files
and we're going to go to the starting
code and look for index.html
and we're going to rightclick this file
and we're going to open with live
server.
And you'll see we have all the HTML and
CSS for this project. So now we're going
to create this using React. We'll start
by creating this main page. We usually
call this the homepage.
By the way, a page or a web page is a
single page like the homepage or the
cart page. A website is a group of web
pages.
To create this homepage, we're going to
move all of the HTML and CSS into React.
We'll go back to VS Code
and we'll open the starting code
index.html.
And this file contains the HTML for the
homepage. And we're going to move this
HTML into the index.html
here for the e-commerce project. So,
let's actually drag this index.html HTML
and we'll open it at the bottom
so we can see these files side by side
and we'll move the HTML in the starting
code into our project one by one.
We already have the doc type HTML inside
here. So we don't need to move it. And
we also have the HTML and head elements.
The first thing that we do need to move
is this title. So we'll select this
title and then cut.
And inside the projects HTML file, let's
replace the title here.
And now we'll keep going one by one.
Next, this meta viewport element makes
the website look good on smaller
screens. Now, we already have this
inside our React setup, so we do not
need to move it over. Let's actually
select this code and delete it so that
we can keep track of our progress.
Next, this code loads a font or a style
of text called rooto.
We're going to use this font in the
e-commerce project. So, we're going to
move it over. Let's select this code
and cut.
And inside our e-commerce project, we're
going to paste.
And if you need to, you can fix this
spacing by selecting these lines and
press shift tab a few times.
Next, these lines of code load the CSS
for our project. Now, remember, when
using VIT, we actually import our CSS
files.
So, we're not going to move these over
for now, but we'll keep these for later.
Finally, if we scroll down, the HTML
inside the body creates the contents of
the page. Now, the contents of the page
should be created by React.
So, let's move this into a React
component.
First, we'll create a component for the
homepage. So, we'll scroll up to the
source folder and we'll click this
folder and we'll create a new file.
Usually, we create a component for each
page of the website. So, let's name this
file capital H home capital Page.jsx.
Now, this website has multiple pages.
So, let's create a folder to group all
the pages together. We'll create a
folder and we'll name it pages.
And we're going to move the homepage
into the pages folder.
And now let's create a component for the
homepage using function. and we'll name
it capital H home capital P page
brackets and curly brackets and we're
going to return brackets
we're going to return the HTML for the
homepage which is right here. So we're
going to copy all of this HTML into our
new component. So, one trick we can do
is on the left, we're going to click
this arrow to collapse this element. And
we're going to click this arrow to
collapse this element as well. And now
we can select all of this HTML code
and cut.
And inside homepage.jsx,
we're going to paste that code.
And now we're going to scroll up and fix
all of these errors.
First, if we collapse this code
and collapse this element,
you can see we're returning two elements
from this component.
But remember, we can only return one
element from a component. To fix this,
we can wrap this in a fragment. So, at
the top, we'll create a fragment using
less than, greater than, and delete this
closing tag. And at the bottom, we'll
create the closing tag less than
slashgreater than. And let's also fix
the indenting here. We can select all of
this code and press tab a few times
until there's an indent before the
fragment. And for the first line, we're
going to remove an indent. And that will
fix the indenting.
Next, we'll fix these errors. We'll
expand these elements.
And remember in React, we have to use
class name instead of class. So to fix
these errors, we need to change all of
these to use class name. To do that, we
can press CtrlF on Windows or command F
on Mac to find some code. And we're
going to search for the code class
equals. And then we're going to click
this arrow on the left. And this will
open the replace menu. So this lets us
replace class equals with something
else. We'll replace it with class
capital N name equals and then press
this button to replace all.
And now you'll see that we fixed all of
the ESLint errors. Finally, we're going
to scroll to the top and we need to
export this component so we can use it
in other files. At the front, we'll type
export and save.
So, we moved all the HTML from the
homepage into our component and we fixed
all these errors. Now, let's use this
component in our app. We're going to go
to app.jsx JSX
and we'll remove this default HTML.
So we'll select it
and delete it
and we'll insert our homepage component.
First we need to import it.
at the top. We'll import curly brackets
the home page
from a string and we'll locate this
file. So, we're going to type dot slash
to start in the current folder which is
the source folder and we'll go into
pages
slashhome
page.
And now we'll insert the homepage into
our app. So here we'll type less than
homepage
slashgreater than. And next we'll fix
these eslint errors. The react logo and
vit logo are not used anymore. So we can
remove them.
Count and set count are also not used
anymore. So we can remove them.
and use state is not used anymore. We
can remove this as well
and save.
And now let's make sure that we saved
all of our other files. So we'll open
index.html
and we'll save it.
And let's open the starting code
index.html
and we'll save this file.
And now let's take a look at our
website. We'll open the browser.
And we can close GitHub for now. And
we'll open the e-commerce project.
And you'll see that we have the HTML and
the text for the e-commerce project
homepage.
Now, obviously, this doesn't look very
good. So, let's move over the CSS. Next,
to move the CSS into our React project,
we're going to go back to our code
and we're going to open the starting
code index.html.
And here we're going to scroll up and we
load three CSS files. So, we're going to
move these three files into our React
project. We'll start with general.css.
If we open styles/shared
which is here and shared and open
general.css
and this file contains CSS for the
overall website. CSS for the overall
website goes into the index.css file in
React.
So we'll click general.css CSS and we'll
press control A on Windows or command A
on Mac to select all of this code and
we'll copy
and index.css in the e-commerce project
we're going to remove all of this
default code
and paste
and save.
And now if we go back to the starting
code, we've moved over general.css and
we can delete this file.
And now we'll go back to the starting
code index.html.
And we can remove this line.
And we'll move header.css and index.css
into our React project. So both of these
style the homepage. So, we'll just move
these files beside our homepage
component.
First, we'll go into styles, shared, and
header.css,
and we're going to drag this file
into our pages folder.
So, we keep our CSS beside the component
that it styles.
And we'll scroll down and find
styles/pages.
And we'll move index.css CSS beside the
homepage as well.
So header.css styles the header at the
top of the page and index.css
styles the main part of the homepage.
Now a best practice is to use the same
name as the component here. So we'll
rightclick index.css CSS and we'll
rename it
capital H home capital P page.
Next, to load these styles, we need to
import them. We'll open homepage.jsx
and at the top,
we're going to import
a string and we'll import the file dot /
header.css. CSS
and we'll also import a string
slashhome
page.css
and save.
And now if we go back to the starting
code index.html,
we moved all of the HTML and CSS into
our project. So now we can delete this
file.
Finally, we'll open app.css.
And these styles were for the default
React website. So we don't need these
anymore. So we can select all of the CSS
and just remove it and save.
So make sure that we saved all of our
files. And now we're going to view the
website.
And now it's looking really good. We
have the structure and the styling that
we need. The only thing that's missing
are the images. So let's move the images
next.
To move the images, we'll go back to VS
Code and we'll go to the starting code
and find the images folder. So this
contains all the images that we need.
So, we're going to move this into the
React project.
Now, usually we put images in the assets
folder and then we import the images.
However, to save time, we're going to
move this folder into the public folder.
So, we're going to move it up here and
into the public folder.
The reason we move it into the public
folder is because if we look at
homepage.js, jsx and we look at an
image. Notice the source attribute
starts with images slash. When using
vit, if we start with a folder name like
this, vit will look for this inside the
public folder. So, it finds it here. So,
by moving our images into the public
folder, we don't have to change any of
this code and it just saves time in the
video. We can move these images into the
source/assets folder and import them
later as an exercise.
So now let's open our website
and all of the images are loaded. So
that's how we move an HTML website into
a React website. We just move over the
HTML, CSS, and images one by one.
Let's go back to VS Code and we'll save
our changes into Git. We'll open the Git
section. And here we moved all the HTML,
CSS, and images for the homepage. We're
going to type a message at the top. Move
the home page into React and press
commit.
Next, we're going to move the checkout
page to the React setup. We'll go to our
browser
and we're going to open the final
project at superimple.dev
and we're going to click the cart icon
in the top right.
This will open the checkout page where
we can see our cart and we can place an
order. So notice that this is a separate
page from the homepage and this page is
also on a different URL/checkout.
So how do we create multiple pages in
React? To do that, we're going to learn
a feature called routing. Routing lets
us create multiple pages in React.
Let's go back to our code
and we'll open our files here.
and we're going to scroll down first to
the starting code folder.
So, normally to create multiple pages,
we need to create multiple HTML files
like here. Each page has its own HTML
file like the checkout page and the
orders page. However, inside these
files, notice that there's a lot of
repeated code. So, each file has the doc
type. it has some meta and link elements
and in the orders.html
it has the same meta and link elements.
So this is not great because if we want
to change something on one page we have
to change all of the pages. On the other
hand, routing lets us create multiple
pages using one HTML file, and this lets
us reuse our HTML code. To use routing,
we're going to install an MPM package
called React Router. So, let's reopen
our terminal. You can click here and
drag up or press control J on Windows or
command J on Mac to open this terminal.
Now we currently have the Vit server
running. So we'll press control C on
Windows and Mac to stop the V server.
And to install React Router, we're going
to run the command npm install
react-rowout.
And we'll also type at. So for this
video, we'll use a specific version of
React Router just to make sure that it
works with the video. So click this link
in the description, go to lesson six,
and here you'll find the version of
React Router that we'll use, and you'll
also find the full command. So again,
you should always use the version that
you see on your page.
So select the version on your page and
copy it. And then in our command line,
we're going to paste that version
and press enter to install.
So now, how do we use React Router? Like
most packages, React Router has a
documentation page that tells you how to
use it. You can find the documentation
in the description, but for the video,
I'm going to show you the parts of the
documentation that we need. According to
the documentation, to use React Router,
we need to load it when we render the
app component.
So, in our project, we're going to
scroll up and open main.jsx,
and I'll close these other files so we
can see more of the code.
So, in this file, we set up React. We
render our app component on the page.
According to the documentation, we need
to wrap this in a component called
browser router.
So at the top first we're going to
import curly brackets
the browser
router
from a string
and we'll import it from the package
react router.
As a review, if we just start with a
name like this without dot slash, this
means it's going to load it from node
modules from the React router package.
And now around the app, we're going to
create less than browser
router greater than.
And we're going to put the app inside
here. So we'll cut this
and paste it in here.
Let's save.
Next, we need to do a bit more setup.
According to the documentation, inside
our app component, we need to add a
component called routes.
So, let's open app.jsx.
And at the top,
we're going to import curly brackets
the component routes
from a string. And we'll import this
from the package react-outer.
And inside this component, we're going
to insert the routes component using
less than routes greater than.
So the routes component tells React all
the pages that are in our website. So to
add a page to our website, we're going
to use another component called route. A
route is basically a page.
So first we need to import that at the
top. We're already importing from React
Router. So we're going to add a comma
and import the route component.
So inside routes, we're going to add
less than route greater than. So again,
a route basically adds a page to our
website.
And we're going to give this route two
props. The first prop is called path
equals double quotes. This tells React
the URL path of this page.
The URL path is the last part of the URL
like /checkout or slash orders. So first
let's add the homepage. For the
homepage, the URL path is empty.
To set the URL path as empty, we're
going to set it to slash.
And then we're going to give route a
second prop called element equals curly
brackets. So this tells React which
element or component to display when we
go to this URL path for the homepage. We
want to display this homepage component.
So let's select it and cut.
And inside here we're going to paste.
So this tells React that when we go to
the URL path slash or empty, it's going
to display our homepage. So let's try it
out. We'll save this file
and then inside the terminal, we're
going to start the VIT server using npm
rundev.
And we'll visit this URL.
I already have it open. So I'll open my
browser.
And now if the URL path ends with slash
or empty, it's going to display the
homepage.
Next, let's use React Router to add a
checkout page. We'll go back to our code
and to add another page to our website,
we're going to use the route component
again. So, we'll create less than route
greater than and we'll give it two
props. the path equals double quotes.
And for the checkout page, we'll set the
URL path to checkout.
This means this page will be displayed
when we go to /checkout.
And we'll give it another prop element
equals curly brackets.
And right now, we didn't create a
component for the checkout page yet. So
let's just create a div here just to
make sure that this is working. So we'll
create a div element and inside let's
type test checkout page and save.
So now if we go to our project
and in the URL path we're going to go to
slash checkout
and press enter.
It displays the div with the text that
we created.
So, as you can see, routing is actually
pretty simple. We just tell React which
pages we want in our website and then
what to display for each page.
Now, let's learn some more details about
routing. If we look at our code, we now
have multiple pages in our website. And
all of these pages use one HTML file
which is index.html.
So this HTML is shared between all of
our pages and this reduces repetition.
By the way, this is called a single page
application or an SPA. This means we
only have one HTML file and instead we
use React to create multiple pages.
Next, we'll use some shortcuts with
React Router. The first shortcut is
instead of path equals slash, React
Router has a prop for this called index.
So, this does the same thing as path
equals slash. The second shortcut is
currently we don't have anything inside
these route components. So, we can use
the self-closing element shortcut. We'll
remove the closing tag.
And at the end here, we'll add a space
and a slash. And same thing here, we'll
remove the closing tag.
And add a space and slash and save.
And now we'll save these changes into
Git. We'll open the git section.
And here it tells us we installed React
Router.
And in app.jsx jsx. We added some routes
or some pages to our website. In
main.jsx,
we loaded the React router. So, let's
create a message to describe these
changes. Create multiple
pages using React-Router
and commit.
Now, let's move the checkout page into
our app. We'll go back to our files
and first we'll open app.jsx.
And instead of displaying a div when we
go to / checkout, let's remove it.
And let's create a component for the
checkout page. Just like the homepage in
the pages folder, we'll click this and
we'll create a new file and we'll name
this capital C checkout capital P
page.jsx.
And inside here, we'll create a new
component using function
checkout
page brackets and curly brackets. and
we'll return brackets
and we'll move the HTML for the checkout
page in here. So, we'll go to the
starting code folder
and we'll open checkout.html.
So, this is the HTML file for the
checkout page.
We're going to scroll down to the body
element first and we're going to move
over this HTML.
So we'll click here to collapse this
code and click here to collapse this
code as well and we'll select all this
HTML and we'll cut
and then inside checkout page inside the
return we're going to paste
and let's scroll up and we'll fix these
errors.
So first if we collapse these two
elements remember we're returning two
elements from this component which
causes an error. To fix this we'll wrap
this in a fragment
and we'll fix the indenting. Now you can
fix it manually like we did before but
you can also use this shortcut. We can
press controlshiftp on Windows or
commandshiftp on Mac and this will open
up a list of commands that we can use in
VS Code. So we're going to search for
the command format document
and we can click it or press enter
and it will automatically format the
code in this document and fix the
indenting.
Next, if we expand these elements,
remember in React, we have to use class
name instead of class. To replace these,
we'll press control F or command F to
find code. And we'll find the code class
equals and click this arrow. And we're
going to replace it with class name
equals and click replace all.
And finally the last eslint error here
is this component is not used in this
file. So we need to export it
and save.
And now let's use this component in our
route. We'll open app.jsx JSX
and at the top we'll import the page
using import curly brackets the checkout
page
from a string and we'll import dot slash
pages slashcheckout page
and we'll use it inside this route using
less than checkout page slashgreater
and save.
And now let's check our website.
And if we go to the path /checkout, you
can see we have the HTML for the
checkout page.
Now, let's add the rest of the code for
the checkout page. We'll go back to VS
Code
and we're going to go to the starting
code and open checkout.html.
and we're going to move this over one by
one. So, first, what do we do for this
title? Right now, all of our pages are
sharing one HTML file here. So, all of
the pages have the same title,
e-commerce project. However, we want
each page to have a different title. So,
how do we do that? Well, in React, it's
actually pretty simple. We just have to
take this title and move it into our
page component. So, we'll select this
and cut.
And then we'll scroll up and open
checkout page.jsx.
And if we want this page to have a
different title, all we have to do is to
paste the title at the top
and save.
So, if we look at our website
now, the checkout page has the title
checkout in the tabs. So, we'll go back
to our code.
And we're also going to set the title in
the homepage. So we'll open the
homepage.
And in the homepage,
let's create a title.
And we're going to set the title to
ecommerce
project and save.
And now we can scroll down
to the index.html HTML
and we can remove this title because
we're going to set it using React
and save.
And now let's move the rest of the HTML
in the checkout page.
If we scroll down here, these meta and
link elements have already been moved to
index.html.
So this is being shared across all of
our pages. So, we actually don't need to
move this over anymore because it's
shared. So, we can remove all of this
code.
And finally, we're going to move over
the CSS for this page
for general.css.
Remember that we already copied these
styles into index.css,
so we don't need to move this anymore.
And now we'll just move checkout
header.css CSS and checkout.css into our
React project.
So, we'll go to styles/pages/checkout
and we'll move checkout header.css
into the React project into here
and scroll down. And we'll also move
checkout.css CSS into our React project
beside the component.
And now that we moved everything over,
we can delete the checkout.html file.
So, we can delete this file.
Finally, let's scroll up
and we're going to rename the CSS file
to match the component name. So, we'll
rightclick and rename.
checkout page.css.
And now we'll load these two CSS files
using import. So in checkout page.jsx
at the top, we'll import a string and
we'll import the CSS file slash
checkout-
header.css.
And we'll also import
dot slashcheckout
page.css
and save.
We'll go to our website.
And now everything looks really good. So
we finished moving all the HTML and CSS
for the checkout page into our React
project.
Let's go back to our code and we'll save
these changes into git. We'll open the
git section
and in app.jsx
we use the checkout page component for
/checkout
and then we moved over the CSS files and
in here we moved over the HTML code as
well as the title. Let's type a message
to describe these changes.
move checkout page into React and
commit.
Before we continue moving pages, there's
an issue that we need to fix. If we open
the website and click the top left icon,
normally this should take us to the
homepage, but now it's blank. So why is
this not working? Notice in the URL the
path is /index.html.
Before this website was split up into
multiple HTML files and index.html
created the homepage.
But now we're using routing. So we set
the URL paths ourselves. In our project
we set the path slash to be the
homepage. and we set the path /checkout
to be the checkout page. So, we need to
go into our code and update all of the
links to go to the correct URL path.
We'll go back to VS Code.
And to update all of our links, we're
going to go to the search section of VS
Code. We can press control shift F on
Windows or commandshift F on Mac.
And here we can search inside all of our
files. First, let's search for the code
index.html.
This will give us a list of a elements
or link elements.
And href means where these links should
go. So now instead of index.html,
these links should go to slash. To
replace index.html HTML in all these
places. We can click this arrow on the
left to open the replace menu. And we'll
replace this with slash. And then click
here to replace all. And confirm.
And let's replace the links for the
other pages as well. So up here, we'll
also search for checkout.html.
And in this search result, we have a
link element with the href
checkout.html.
And in our router, we set the URL path
for the checkout page to /checkout.
So we'll replace all of these with
slashcheckout
and replace all.
And we'll do the same thing for the
orders page, which is orders.html.
And here we'll change it to slash orders
and replace.
And finally, we also have a tracking
page. So here we're going to search for
tracking.html
and replace it with slash tracking and
replace all.
And now all of our links should work
correctly because they match our router.
If we open the website
and at the top we change the URL path to
/checkout
it opens the checkout page. If we click
the top left icon
this should now go to the URL path slash
or empty and it will open the homepage.
So let's save this into Git. We'll open
the git section
and we just updated all the links in
these files to match the router.
Let's type the message update links to
match the router and commit.
Next, let's move the orders page into
our React project. Feel free to pause
the video if you want to try it yourself
first. So, we'll go back to our files
and first let's create a component for
the orders page. Inside the pages
folder, we'll create a new file and
we'll name it orders page.jsx
and press enter.
And inside here we'll create a component
function
orders page brackets and curly brackets.
And we'll return brackets
and we'll move over the HTML. So we'll
go back to the starting code folder and
open orders.html.
We'll start with the body. So we'll
scroll down and we can collapse these
two elements and we'll select the HTML
and cut
and inside the orders page inside the
return we'll paste.
We'll scroll up
and collapse these elements
and we're going to wrap these in a
fragment less than greater than and
remove this. and at the end less than
slashgreater than.
And to fix the indenting, we can use the
shortcut control shiftp or commandshiftp
and search for the command format
document and press enter.
Again, we need to rename class to class
name. So, we'll press control F or
command F to find code. We'll search for
class equals. Click here and replace it
with class name and replace all.
And finally, at the top, we'll export
this component.
Let's save this file.
Let's go back to orders.html.
Scroll up and we'll move over this code.
So, for the title, we're going to move
it into the component. We'll select it,
cut, and at the top in orders page,
we're going to paste it at the top.
Let's go back to orders.html.
And these meta and link elements are
already inside index.html.
So, we can remove this.
And finally, we'll move the CSS files
over. So, general.css CSS was already
moved into index.css.
We already moved over header.css up
here. So, we just need to move the
orders.css.
So, inside starting code, we'll go into
styles/pages
and we'll move this orders.css file.
So, we'll move it up here
beside the orders page component.
And now we moved over everything inside
orders.html.
So we can scroll down and delete this
file.
Next, we should rename orders.css
to match the component name. So we'll
rightclick and rename
orders page.css.
And finally, we'll load the CSS files.
So, in orders page.jsx
at the top, we're going to import a
string. And remember, this requires the
header and the orders page CSS.
So, first we'll import dot slash
header.css.
And we'll also import
dot slash orders page.css. CSS and save.
And now we moved over all the HTML and
CSS for the orders page.
So now let's create a route for this
page. We'll go to app.jsx.
And first at the top we're going to
import curly brackets the orders page
from a string. and we'll locate dot
slashpages slash orders page and then
down here we're going to add another
route. So at the end we'll add less than
route greater than and we can remove
this
and use the self-closing element
shortcut
and we'll give it two props. We'll set
the path equals double quotes and we'll
put the orders page on the path slash
orders
and we'll give it an element to display
equals curly brackets. And for the
orders page, we'll display the element
less than orders page slashgrater than
and save.
And now let's view the website. We'll
open the website
and on the homepage we're going to click
this orders link to go to slash orders
and it displays the orders page. So that
looks pretty good. And now we finished
moving the orders page into React.
So let's go back to VS Code.
And in the starting code, there's one
more page to move over, which is the
tracking page. But I'll leave this as an
exercise.
So now let's save these changes into
Git. Open the Git section.
In app.jsx, we added a new route for the
orders page and we moved over the CSS
and the HTML.
So we'll type the message move orders
page to React
and commit.
Next, we're going to separate our page
into smaller components.
For example, if we look at our website,
notice that on the orders page, there's
this header at the top. And if we click
the top left and go to the homepage, we
have the same header at the top of the
page. So, it's a good idea to separate
the header into a component so we can
reuse it between these pages. We'll go
back to VS Code
and we'll open our files and we're going
to open homepage.jsx.
And at the top here, we have the HTML
for the header. If we collapse it, this
is all the HTML for the header.
Let's separate this into a shared
component.
Now, because this component is shared
between multiple pages, we usually put
shared components in a folder called
components. So, inside our source
folder, we're going to click it and
create a new folder
and we'll call it components.
So the components folder is for shared
components and the pages folder is for
components that are specific to a page.
Inside the components folder, we'll
create a new file.
And let's name it header.jsx.
And in here we'll create a component for
the header using function
header brackets and curly brackets. And
we'll return brackets.
And we'll move over the HTML.
So we'll open homepage.jsx JSX
and we're going to select the HTML for
the header and cut
inside header.jsx.
Inside here, we're going to paste.
And we'll fix the indenting by pressing
control shiftp or command shiftp and
search for format document and press
enter.
And we'll scroll to the top. And lastly,
we're going to export this component to
remove this error.
Next, we should also move over the CSS
for the header. Now, luckily the CSS for
the header has already been separated
into header.css.
So, we can just move this over to beside
the component.
So, we want to keep the CSS close to the
component so it's easy to find. So at
the top of this we can import the CSS
using import a string and we'll import
dot slash header.css
and save.
So now that we created this header
component, we can reuse it in the
homepage and the orders page. We'll open
homepage.jsx.
And at the top first, we don't need to
import the header anymore. It's already
done by this component. So we can remove
it. And let's import the component using
import curly brackets. The header
from a string.
And now we need to locate this file. So
currently we're inside the pages folder.
So we need to get out of this folder
using dot dot slash and then go into the
components folder. components slash
header.
And now we'll use this component in the
HTML. So down here
we'll insert less than header
slashgreater than and save.
So now this HTML is a bit easier to work
with because we split it up into smaller
pieces. Let's do the same thing with the
orders page. We'll open the orders page.
jsx
and at the top we don't need to import
header.css CSS and instead we'll import
curly brackets the header component from
a string and we'll locate dot dot slash
components
slash header
and down here instead of this HTML we
can remove this and just use the
component less than header slashgrater
than this helps us reuse and save a lot
of code. Let's save
and then view the website.
The header looks good in the homepage.
And if we click here to go to the orders
page, the header also looks good in the
orders page. So, we're able to reuse the
header component.
Next, there's a small issue with the
header. when we click a link like this
link in the top left, it actually
reloads the page when we go to another
page. So by default, link elements or a
elements reload the page. Now this made
sense before when our website had
multiple HTML files. To go from one file
to another file, we have to reload the
page. However, now that we're using
routing and a single page application,
we don't have to reload every time, we
can just use JavaScript to switch
between pages.
To do this, React Router provides a
component called link. So, we'll go back
to our code
and we'll open the header component
and at the top
we're going to import
curly brackets
the link component from
the package react-rowout.
So, the link component lets us go to
another page without reloading.
To use it, we just have to replace our
link elements or a elements with this
link component. So here, let's replace
this with link and at the end slash
link.
And also instead of the href attribute,
the link component uses a prop called
to. So this will link to this page.
Let's scroll down
and in the header we have two other
links, the orders link and the cart
link. So we'll switch both of these as
well. So here we'll switch it to link
and slashlink
and we'll switch the href to two.
And finally, switch this to link
and slashlink
and switch href to two and save.
And now let's open our website to try it
out.
If we click this link to go to the
orders page, you'll notice it's a little
bit faster because now it's using
JavaScript to essentially display a
different page without reloading.
So when using React Router, we should
use the link component instead of the A
element because the link component lets
us go to another page without reloading.
Now let's save these changes into git.
We'll go to the git section
and here we split up the header into a
separate component. And then inside the
header, we switch to using the link
component to switch between pages.
Let's type the message
split header into a component
and use link and commit.
In the next lesson, we'll add a backend
to this project and make it interactive.
So, we'll be able to display a list of
products and add products to a cart and
create an order. And that's the end of
this lesson. In this lesson, we started
the ecommerce project using React and
Vit. We reviewed Git, which helps us
track changes in our code. We learned
routing, which lets us create multiple
pages in React. We created the homepage,
the checkout page, and the orders page
in React. We updated all the links to
work with routing, and we separated the
header into a component.
Here are some exercises to help you
practice what we learned in this lesson.
In this lesson, we're going to start
making our e-commerce project
interactive and then we'll learn how to
use a backend with this project.
By the way, if something in this lesson
does not work for you, you can check the
troubleshooting guide in the
description.
First, if we look at our website,
currently we only have three products on
this website, but in the final project,
we have a lot more products. So, we're
going to add all of these products to
our website. So, let's go to the code
for the homepage.
We'll open our code and go to the files
and we're going to find the pages folder
and open homepage.jsx.
So this component represents the
homepage. And we're going to scroll down
and find the element with a class
product-container.
And we're going to click here to
collapse this element. And we're going
to collapse this other product
container. and this other product
container as well.
Each product container represents one
product on the page. To add more
products, we could make a copy of this
code and add each product manually.
However, that would be very repetitive.
Instead, we can generate this HTML using
React. We already learned this technique
in the chatbot project where we
generated a list of chat messages on the
page. So, we're going to review how to
generate the HTML.
First, we need to save the data for
these products in our JavaScript. To
save time, I already did this. So, if we
go to our files and we go to the
starting code folder
and we open this data folder inside
products.js, JS I already saved the data
for the products in this array. So we
can just use this as our data.
Each object in the array represents one
product. So it has a name, an image, and
a price and some other details. The next
step is to use this data to generate the
HTML. We'll go back to the homepage
and first we're going to import that
products array. So at the top we're
going to import curly brackets the
products array from a string and we're
going to locate that file. So first we
need to get out of the pages and source
folder using dot dot dot slash and then
we'll find the starting code folder and
the data folder. starting dashcode slash
data slash and the products file.
Next, we're going to loop through this
products array. So, at the bottom here
above these product containers, we're
going to insert using curly brackets the
products array dot map and brackets. And
we're going to give map a function
brackets arrow and curly brackets.
As a review, do map takes each value in
an array and transforms it. In this
parameter, we get each value in this
array, which is a product.
So again, a product is just this object
and it has some details about the
product inside.
So, we'll go back
and we're going to transform this
product object into this HTML.
To do that, we're just going to copy
this HTML
and inside map, we're going to return
brackets
and paste that HTML.
And to fix the formatting, we're going
to press control or commandshiftp
and then search for format document
and press enter.
And let's scroll up.
And remember, whenever we loop through
an array like this, we need to give each
element a key prop equals curly
brackets. So the key helps React keep
track of changes in this array. Now the
key has to be unique. So looking at the
data, each product has a unique ID
property.
So we'll go back and we're going to use
the product. ID as the key. So this
basically takes each product object and
transforms it into this HTML.
So now let's save
and we'll check the website.
And as you can see, we took each product
and transformed it into some HTML.
Now, obviously, we don't want the
product to be socks every time. So,
let's insert the details of each
product. We'll go back to our code, and
instead of displaying the socks every
time, we're going to remove this. and
insert.
And each product object has a name
property. So we'll insert the
product.name.
And let's also replace the product
image. So instead of showing the socks
image every time, we'll remove this and
we'll insert the product.
Property.
Next, we'll insert the ratings. The way
this works is that each rating has an
image. And we just have to multiply the
rating by 10 to get the image name. So
for this one, we're going to put open
curly bracket and close curly bracket
around this value. And we're going to
change this to a template string using
back ticks and back ticks. And then
instead of 45 every time, we're going to
insert. And remember for template
strings to insert we use dollar curly
brackets. So in here we're going to
insert the product dot rating dot stars
and then multiply it by 10. And this
should give us the ratings image that we
need. Next we're going to replace the
rating count. So curly brackets and
we'll insert the product.
count.
Next, we'll insert the price. So,
instead of this price every time, we'll
insert the product dot price sets. And
we usually save money in cents because
many programming languages have trouble
calculating decimal numbers. Now, when
we display it on the website, we want to
display it as dollars. So to convert
this back to dollars, we're going to
divide by 100 since $1 is equal to 100.
And that's it. We inserted the details
of each product into this HTML.
This is the same technique that we used
in the chatbot project, except our data
is just a little more complicated. Now,
let's save
and check the website.
And now we have a list of different
products on the page and we generated
the HTML for these products. Now there
is a small problem here which is for
these socks it's showing the price 10.9
but usually for price we want to show
10.90.
To fix this, we'll go back to our code
and we're going to scroll down to where
we insert the price. And to force this
to show two decimals, we're going to
wrap this in a open bracket and a closed
bracket. And then outside of this
bracket, we'll use the method dot two
capital Fixed
and brackets.
So this converts the number into a
string and inside these brackets we can
tell it how many decimals to show. So
we'll put two
and save.
Now if we check the website
all the prices show two decimals. So
that's a review of how to generate the
HTML using some data. Let's go back to
our code.
And now that we're generating all this
HTML, we can scroll to the bottom and
remove this default HTML that we had
before and save.
And now let's save these changes into
git. We'll go to the git section and at
the top we'll use a message generate the
HTML for the home page and commit.
Now, we're going to take this project to
the next level and go beyond what we did
in the chatbot project. We're going to
add a backend to this project. So, first
we'll learn what a backend is and why we
use a backend. So, right now, if we look
at our files,
notice that all the products are saved
in a file on our computer called
products.js. JS.
The problem with this is an e-commerce
website or an online shopping website
might have thousands of products and it
does not make sense to save everything
on our computer or on the customer's
computer. We might not have enough space
on our computer. So, what the company or
the store does is they set up another
computer in their office or in what we
call a data center. And this computer
saves all the thousands of products that
they offer. And then when we visit the
website, this computer sends us only the
products that we need to display. So
this computer is called the backend.
It's just another computer that's owned
by the company and it manages all the
data.
Here's another example of why we use a
backend. Later in this course, we're
going to add products to a cart. So,
where do we save this cart? It does not
make sense to save the cart on the
customer's computer because if the
customer uses a different computer to
visit the website, they would no longer
have access to their cart. Instead, we
save the cart in the back end as well.
When they access the website, the
backend sends the cart to the website.
So, the back end also lets us share data
between computers.
So again, the backend is another
computer that manages the data. And this
is how a React website works in the real
world. We usually contact a backend to
get the data. So we're going to practice
that in this course. We're going to
learn how to add a backend and then
we're going to learn how to use the
backend in React. So you can see how we
use React in the real world.
Now that we learned what a backend is
and why we use a backend, let's add a
backend to our project. We're going to
click this link in the description. Go
to lesson 7 and click this link to open
the backend code.
And this is a backend that we can use
with our project. I called it the
e-commerce backend AI because this was
built with AI. And I show you how to do
that in another video. But for this
video, I recommend downloading this
version to make sure it works with a
video. You can try to recreate the back
end as an exercise. So, we're going to
click this code button here and we'll
click download zip.
Once that finishes downloading, we're
going to open the downloads folder. So,
for me, it's right here. And then we're
going to unzip this. On Windows, we're
going to rightclick the file and then
click extract all.
And on Mac, you can just doubleclick the
zip file.
Then we're going to move this back end
into our project. So we'll open our
code.
And then we're just going to drag this
folder into our project. But first, I'm
going to collapse these folders for now.
And we're going to drag this folder to
the outside
and click copy folder
so that the backend code is right beside
our website. By the way, we call the
website or what the user interacts with
the front end.
We're also going to rename this folder.
So, right click and rename.
and we'll just rename it the e-commerce
backend to make it easier to understand.
Next, we're going to start this backend.
So, we're going to go to our terminal or
our command line and we'll click here to
create a new tab. And then in here,
first we're going to change directory
into the e-commerce backend folder. So,
we'll cd ecommerce
dashbackend.
So now the command line is running
inside this folder and the process for
starting the back end is very similar to
the website or the front end. So first
we're going to npm install to install
all the npm packages that we need
and then we'll run npm rundev to start
the back end.
So, this tells us the back end is
running on port 3000, which is localhost
col 3000. To test it, we're going to go
to our browser,
and at the top, we're going to create a
new tab, and we're going to go to
localhost
col 3000
/s.
And the back end should send back some
data.
And this is actually the data for the
products.
I can also click this checkbox here to
show it in an easier to read format. And
you can see this is the same products
array that we were using before except
this is coming from the back end. So the
way a backend works is when we access
the backend using a URL, it will send
back some data. So this is working.
So now let's go back to our code and
we'll save these changes into git. Open
the git section and we'll use the
message add ecommerce
backend and commit.
Next we're going to learn data fetching.
Data fetching means to get data from the
back end using our code. So, first we're
going to go to our files and let's go
back to the e-commerce project. And
we're going to open our homepage,
which is right here.
And we'll scroll to the top. And one way
to fetch data or to get data from the
back end is to use the function fetch
and brackets.
So fetch is a built-in function. It's
provided by JavaScript.
between the brackets, we're going to
create a string
and we're going to put the URL that we
want to get data from. So, if we go back
to our browser,
remember that this URL gave us the
products data. So, we can just select
this URL and copy.
And in our code, we're going to paste it
into fetch.
And make sure you have http col double
slash in front. It doesn't show in the
browser, but we need this in order for
our code to work. So if we fetch data
from this URL, this should give us the
products data that we saw earlier.
However, we cannot save this data in a
variable like this. And that's because
when we contact a backend, it takes time
for this code to reach the back end and
to get a response. So this code does not
finish right away. It finishes at some
point in the future. As a review, we
call this asynchronous code.
Asynchronous code means code that does
not finish right away. So how do we
handle this situation?
fetch returns a promise and a promise
lets us wait for asynchronous code to
finish.
So a promise has a method called dot
then and brackets and we give dot then a
function brackets arrow and curly
brackets.
The way this works is that this code
contacts the backend to get some data
but it takes some time for the backend
to respond. So the code is going to keep
going line by line. Then at some point
in the future, this is going to finish.
We're going to get the response from the
back end. When it finishes in the
future, it will run the function inside.
So that's a review of how a promise
works. So next when fetch gets a
response from the back end it will save
it as a parameter in this inner function
called response.
By the way when we contact the back end
using fetch this is called a request.
When the back end responds with some
data this is called a response. So this
parameter contains the response from the
back end. And inside here, let's just
console.log
the response to see what it looks like.
We'll save
and then check our website
and we'll open the tab for our website
and we're going to open the console.
Rightclick, inspect,
and the console.
And you can see that we got the response
from the back end. So inside here we
have some information like the URL that
we accessed and a status code. 200 means
it was successful.
However, notice that we don't have the
products data in this response. To get
the products data, we're going to go
back to our code
and this response object has a method
called response.json
JSON and brackets.
So,JSON gives us the data that is
attached to the response. In this case,
it gives us the products data. Now, the
tricky part about this is response.json
is also asynchronous. So, again, we
can't save this in a variable. Instead,
this is also a promise. So we have to
use dot then again and give this another
function brackets arrow and curly
brackets
and then inside this inner function we
have access to the data that we get from
the back end. So in this case this is
the products data.
So if we console.log log the data and
save
and then check the console.
You'll see that the backend gave us an
array of products to display on the
page. So, this is the same thing as the
products array that we saved in our
file, but this data is coming from the
back end.
Let's go back.
And that's how we fetch data or get data
from the back end. We use the built-in
function fetch and give it the URL of
the back end and then we use dot then to
wait for a response.
Now one shortcut we can use is instead
of doing dot then inside another dot
then we can also return the
response.json JSON and then move this
dot then to the outside.
So this code does the same thing as
before. This waits for this to finish
and then runs this function. So this is
just a shortcut that we can use with
promises.
Another thing to note is the back end
can also run on the same computer as the
website or the front end. So right now
this back end is actually running on our
own computer. Locost means our own
computer. So when we contact the back
end, we're actually just contacting our
own computer. We do this during
development because it's easier. But
once this website is on the internet,
the back end will be another computer.
So now let's save this code
and we'll save this into git. In the get
section, we'll use the message fetch
data from the back end and commit.
Next, notice that using fetch is still a
little hard to read. We use a and then
we use response.json and then another.
To make this code cleaner, we're going
to use an npm package called Axios.
Axios is a cleaner way to make requests
to the back end. First, we're going to
go to our command line and we'll open
the tab for the front end. And here
we'll press Ctrl C to stop the V server.
And we're going to npm install Axios and
type at and we're going to give it a
version. So, we can click this link in
the description and then go to lesson 7.
And this is a version of Axios we're
going to use. So, again, you should
always use the version that you see on
your page.
So, select the version on your page and
copy it
and then paste it in our code and press
enter to install Axios.
Once that's installed, we're going to
run mpm rundev to restart the vit
server.
And then to use axios in our code, we're
going to go to the homepage. And at the
top, we're going to import axios without
curly brackets from a string axios.
And now instead of using fetch, we're
going to use axios.get.
So this does the same thing as before
except the data from the back end will
be saved directly inside the response.
So instead of doing all these steps,
we can just get the data using response.
So let's console.log this to see if it
works. So console.log and save.
And then if we open the console,
you'll notice it gets the same products
data as before.
But if we look at our code, it's a lot
cleaner because we can just get the data
directly from the response. So as you
can see, Axios is a cleaner way to make
requests to the back end. So now let's
save this into git. In the get section,
we'll use a message use Axios to fetch
the data and commit.
Now, let's use this data from the back
end to generate the HTML instead of
using the products file that we had
before. But first, we have a problem.
This code is directly inside the
homepage component. That means whenever
the homepage changes or rerenders, it
will run this code again and send
another request to the back end.
However, we just need to load the
products once on this page. We don't
need to load the products over and over
again. To make this code run once, we
can put it inside a use effect. At the
top, we're going to import curly
brackets use effect
from React.
And above this code, we're going to do
use effect brackets and give this a
function brackets arrow and curly
brackets.
Use effect lets us control when some
code runs. We're going to move this code
inside the use effect. So we'll cut and
in here we'll paste.
And I'll select these lines and press
tab to reformat.
By default, use effect runs this code
every time the component is created or
updated. But we can control this. At the
end of this function, we're going to add
a comma and an empty array. As a review,
this is called a dependency array. The
dependency array lets us control when
use effect runs. If we use an empty
array, that means this code will only
run once after the component is created.
And that's exactly what we need here. We
just need to load the products once on
this page. By the way, you might notice
in the console that use effect runs
twice instead of once. So, this is
totally normal and it's caused by using
strict mode in our app. Strict mode runs
use effect twice to help us catch bugs
and it only does this during
development.
So now that we have the data, how do we
use it in this loop down here to
generate the HTML?
To do that, we need to save the products
data inside the state. So at the top,
we're also going to import use state
from React.
And at the top of our component, we're
going to do const square bracket equals
use state and brackets.
As a review, use state gives us an array
with two values. The first value is the
name of the data. In this case, we'll
name it the products. And then we'll
type a comma. And the second value of
use state is the updater function. The
updater function lets us update this
value and then it will regenerate the
HTML. We usually name the updater
function set and then the name of the
data capital P products.
And finally between these brackets we're
going to put the starting value of the
products. Let's just use an empty array.
And now after we get the products from
the back end, we're going to save it
into the state.
So instead of console.log, we'll use the
updater function set products. This will
save the products data into here. And
then it's going to use this to generate
the HTML. So now we're using data from
the back end to generate the HTML. And
we don't need to import this file here
anymore.
So the only thing to note is that the
name of the data has to match the name
that we use down here. So that this code
is actually using the state.
Now let's save
and we'll check the website.
And everything still works except now
we're using data from the back end to
generate this HTML.
We'll go back to our code
and we'll save this into git. In the git
section, we'll create the message use
data from the back end to generate the
HTML and commit.
Next, if we look at the website
in the homepage, we also need to get the
cart from the back end because we need
to display this quantity number up here.
To do that, we'll go back to our code
and we're going to make another request
to the back end to get the cart. So,
below this request, we're going to use
axios again. Axios.get get brackets a
string and we'll give it the URL http
colhost
col 3000
slash API/cart-
items.
The way this works is the back end is
running on http localhost col 3000 and
after this we add a URL path. Each URL
path gives us different data. For
example, the URL path/ API/proucts
gives us the products data. The URL
path/ API/cart items gives us the cart
data. So the URL path can actually be
anything we want. Whoever creates the
backend decides what the URL paths will
be. In the description, you can find a
documentation page for my backend.
And this lists all the URL paths that we
can use. A common naming convention is
to start the URL path with slash API.
API means application programming
interface. Starting with / API makes it
clear that these URL paths are
specifically for interacting with the
backend.
So we already learned how to use /
API/roucts.
Now we're going to learn how to use /
API/cart items.
And remember whenever we make a request
to the back end it's going to take some
time to get a response. So we need to
wait for this code to finish using then
we'll give this a function
and the response is going to be saved in
here.
So when we make a request to /appi/cart
items, we're going to get the cart in
the response. So in here, let's
console.log
the response data to see what the cart
looks like. We'll save
and we'll check the console.
And you might need to refresh. And the
back end responded with an array. And
this array represents the cart that we
have on the website. So each item in the
cart contains the product ID that we
want to buy and the quantity of that
product. So next we're going to use this
to calculate the quantity and display it
on the page. So we'll go back to our
code and first we need to save this cart
into state so we can use it to create
the HTML.
At the top, we'll create another state
const brackets equals use state
brackets.
And this state will save the cart,
comma, and the updater function set
capital C cart.
And let's set the starting value of the
cart to an empty array. And we'll scroll
down. And now once we get the cart from
the back end, we're going to save it in
the state. So instead of console.log,
we're going to use the updater function
set cart. And now the cart from the back
end will be saved inside this variable.
And remember that the quantity for the
cart is inside the header. So we need to
pass the cart into the header using a
prop. So here we'll add a prop. cart
equals curly brackets and we'll give it
the cart.
Let's save this file
and we'll go into our code and go to
components header.jsx
and then inside the header we're going
to get the cart from the props. To do
that at the top, we'll type curly
brackets and the cart. As a reminder,
this is a shortcut for this code.
And now we're going to calculate the
total quantity in this cart. So at the
top, let's create a variable. Let total
quantity equals zero to start. And then
we'll loop through the cart using cart
for each brackets. And we'll give it a
function.
And the inner function will get one
parameter which is each item in the
cart. So, we'll call this the cart item.
And then each cart item has a quantity.
So, we're going to add that to this
total quantity up here. We'll do total
quantity plus equal the cart item.
And now we can scroll down
till we see the cart quantity down here.
And instead of three every time, we're
going to insert the total quantity
and save.
And now if we look at our project
now, it will display the total quantity
using data from the back end. So now
let's go back to our code.
And if we scroll up, you might see an
error here for props validation. Again,
this is an older feature of React. So,
we can disable this check by going into
our files and opening eslint.config.js.
And then we'll scroll down inside this
rules object. We're going to add a
string react/prop-
types colon the string off. So, make
sure it's inside this rules object. We
can save.
And now if we go back to the header, the
props validation error should be gone.
So now let's save this code into git.
We'll open the git section and we'll
create a message get cart from the back
end and display quantity and commit.
Next, if we go back to the homepage, so
in our files, go to pages and homepage
and scroll up. Notice that for each
request, we're sending it to localhost
3000. So, we can actually set up a
shortcut in Vit. So, we don't have to
type localhost 3000 every time. So, we
can actually remove these
and save.
And then we're going to go to our files
and we're going to open vit.config.js.
And inside here we're going to add the
property server colon and an object. And
inside we'll add the property proxy
colon another object.
And in here we'll add a string slash API
colon. And we're going to give this an
object. And inside we'll add a target
property colon and the string http colon
double slash localhost colon 3000.
So this is called a server proxy
configuration. This just means that if
the URL path starts with / API like we
had it before, the request will
automatically go to localhost 3000. So
we don't have to type it every time.
Another thing we can set up is when we
load images, we also want to load them
from the back end. Remember the back end
should manage the data including the
product images. So in here we'll also
add a comma and add a string slash
images colon and an object
and we'll give it the same target. So
we'll select this and copy and in here
we'll paste
and save.
And we need to do one more thing. We're
going to go inside index.html HTML and
in the head we're going to add less than
base slashgreater than and we're going
to give this an attribute href equals
double quotes and a slash.
So this adds slash in front of any
relative urls. All the image URLs start
with images and this will convert them
into slash images so that our redirect
will work. Let's save
and we'll go back to the vit config.
So now when we get images, we're going
to get them from the back end. And now
because we changed the vit
configuration, it's a good idea to stop
the server with control c and then
restart the server using mpm rundev.
And now let's check the website to make
sure everything is working. So I'll just
refresh this to make sure. And
everything still looks good. So now
we'll go back to our code and we'll save
these changes into git. Inside git,
we're going to type the message add
server proxy config for slash API and
slash images
and commit.
Next, we're going to move on to the
checkout page. So, let's open the
website and we'll click the cart icon in
the top right
and we're going to work on this page.
So, on this page, we also need the cart
to generate this HTML.
So, we'll go back to our code
and we'll open our files and we're going
to open checkout page.jsx.
And now inside here we could do another
axios.get/appi/cart
again. But remember we already loaded
the cart on the homepage. It does not
make sense to reload the cart whenever
we switch pages. We just need to load
the cart once for the entire website. To
do that, we're going to go to the
homepage
and we're going to share this cart
between the two pages using the
technique lifting the state up. As a
review, this means we move the cart
state up to an outer component. In this
case, the outer component is the app
component here, which contains a
homepage. So, we're going to lift the
cart up into the app component. And from
here, we can share the cart between the
homepage and the checkout page. So,
first, let's go into the homepage again.
We're going to select this cart and cut
and go back to the app. And we're going
to lift it up in here by pasting it. And
we also need the code that loads the
cart. So in the homepage,
we're going to select this code and cut
and save
inside app.jsx.
Below this, we're going to paste.
And remember, we need to put this inside
a use effect so that it only runs once.
So use effect brackets, give it a
function,
and a empty array at the end. And we're
going to select it and cut. And inside
here, paste.
And I'll select these lines and press
tab to reformat them. And next, we'll
need to import this code. So at the top,
we're going to import curly brackets,
use state, and use effect
from React.
And we'll also import axios. So at the
top again, we're going to import axios
from the string axios.
So now that we have the cart, we're
going to share it between these two
pages using a prop. So for the homepage,
we'll add a prop. Cart equals curly
brackets and we'll give it the cart. And
for the checkout page as well, cart
equals curly brackets. and we'll save
the cart.
Let's save this file.
And we'll go into the homepage.
And at the top, we need to access the
cart from the props using curly
brackets, the cart, and save.
So, the code should work the same as
before, except we're just getting the
cart from the props. Now, let's open our
website to make sure it works. We're
going to go to the homepage and refresh.
And that looks good. We'll go back to
our code. So now that we lifted the
state up, we can just load the card once
for the entire website instead of
reloading it on every page. We'll open
the get section and we'll give it the
message lift cart up and share it
between pages and commit.
Next, we're going to use the cart to
generate the HTML for the checkout page.
So, first make sure that we pass the
cart to the checkout page using this
prop. And now we're going to open the
checkout page, which is here. And we're
going to access the cart from the props
using curly brackets and the cart.
And I will use this cart to generate the
HTML down here. Now inside this code,
we're going to press Ctrl+F to find some
code. And we're going to search for
cart- item-container.
And here we're going to collapse this
element. And we'll collapse this element
as well.
So each of these represents a cart item
on the page. So let's generate this
using the cart. Above this we're going
to insert cart map brackets and we'll
give it a function brackets arrow and
curly brackets. And this inner function
gets one parameter which is the cart
item. And for each item we're going to
return brackets some HTML.
So for each cart item, we want to
generate this HTML. So let's just select
it and copy. And inside here, we're
going to paste.
And to fix the formatting, we're going
to press control or commandshiftp
and run format document.
Now let's scroll up.
And remember, when we loop through an
array, each element needs a key
property.
Each cart item has a product ID which is
unique. So we're going to save the key
as cart item.
ID.
And now instead of showing the same
product every time, we're going to
insert the details from each cart item.
However, there is a problem here.
Remember that the cart looks like this.
It doesn't have any product data on it.
To fix this, we're going to go to the
app component where we load the cart.
And at the end of this URL, we can add
question mark expand equals product.
So this is called a query parameter. A
query parameter lets us add additional
information to our request. When the
backend receives this query parameter,
it's going to add product details to the
cart. So, it's going to expand the cart
with product details. So, now let's save
this file
and we're going to open the website and
we're going to go to the checkout page
and we're going to open the console. So,
we'll rightclick inspect
and inside the console we're going to
open the network tab.
So, I'm going to remove any search that
I have. And in here, we can see all the
requests that we make to the back end
and the responses. So, by the way,
requests only show up here if the
console was open before the request. So,
we may need to refresh
to get the request to show up in the
network tab. And now we can see our
request to cart- items. If you don't see
it, you may need to search for it up
here by typing cart. And we have it
here. So we can open this by clicking it
and then go into the response tab. And
here you can see the response from the
back end. So now you can see that each
cart item has a property called product.
And this contains all the product
details that we need for this page.
So now let's go back to our code.
And we're going to go to the checkout
page.
And now instead of the socks every time,
we're going to remove this
and insert the cart item.
And we'll also replace the image. So
we'll remove this and insert the cart
item.
image and down here we're going to
insert the price. Now, if we go to the
homepage,
remember that in the homepage, we wrote
some code here to display the price. So,
let's actually move this code into a
function so we can reuse it. Inside our
files, we're going to click the source
folder and we'll create a new folder and
let's call it utils for utilities.
And inside the utmost folder, we'll
create a new file and we'll name it
money.js.
So this file contains utilities or code
that helps us work with money. So in
here, let's create a function and we'll
name it format money brackets and curly
brackets.
And we're going to copy the code from
the homepage. So, inside the homepage,
we're going to take all of this code and
copy it.
And inside money.js, inside here, we'll
paste it.
And now we're going to turn this into a
string. At the front, we'll type backick
and at the end a back tick to create a
template string. And remember in
template strings to insert something, we
need dollar curly brackets. And now,
instead of getting the product.pricent
price cents. We're going to pass it into
this function. So, let's name the
parameter amount cents. And we're going
to remove this and replace it with
amount cents. So, this function lets us
convert any amount cents into this
format. At the end, let's return this
value from the function. and we'll
export it so we can use it in other
files and save.
So now we can go back to the homepage
and at the top we're going to import
curly brackets the format money function
that we just created from a string and
we're going to locate the utils folder.
So, we'll go out of this folder with dot
dot slash utils slashmoney.
And now we'll scroll back down
and instead of this code, we're going to
remove it and insert format money
brackets and we'll give it product.pric
sets and save.
And now let's reuse this function in the
checkout page. So, we'll open the
checkout page, and at the top, we're
going to import curly brackets, the
format money function from a string, and
we're going to locate this file. And for
me, I'll go out of this folder using dot
dot slash utils/money.
Now, if you did the exercises from the
previous lesson, this file might be
inside a folder called checkout. In that
case, make sure you have two dot dot
slash in front. And now we're going to
scroll back down
and we're going to replace this money
with curly brackets.
Format money brackets. And we're going
to give it the cart item.
price sets and we'll replace the
quantity. So, insert
cart item dot quantity and save.
And now if we go back to the website,
now we are generating these cart items
using data from the back end. And this
was the default HTML we had before. So
now we can go back to our code and we
can scroll down
and we can remove the default HTML
and save.
So now let's save these changes into
git. We'll open the get section
and at the top we'll type the message
generate
HTML for the cart items and commit.
Next, we're going to generate the HTML
for the delivery options. So, we'll go
back to the checkout page and we'll
scroll to the top of this component. And
here we'll load the delivery options
from the back end. So first let's import
Axios. At the top we'll import Axios
from the Axios npm package. And we'll
also need import curly brackets. Use
state and use effect to save the
delivery options. So import it from
React.
And now inside the component
we'll create some state to save the
delivery options const
bracket equals use state and brackets
and we'll name this delivery options
colon and the updater function set
delivery options
and we'll set the starting value to an
empty array. Next, we'll get the
delivery options from the back end. So
here we'll do use effect brackets and
we'll give it a function brackets arrow
and curly brackets. And at the end we'll
give it a comma and an empty dependency
array so that this code only runs once
on this page. And inside here we're
going to call axials.get
get brackets and the URL to get the
delivery options is slash API slashd
delivery-options
and then we're going to wait for the
response to come back using then
brackets and give it a function brackets
arrow and curly brackets and inside the
function the response from the back end
will be saved as the response parameter.
So once we get this response, we're
going to save it in the delivery options
up here using set delivery options
brackets
response.
Now let's save this code and we're going
to check the network tab to see if it
works. So, we'll open the console and
we'll open the network tab. And we might
need to refresh to make sure we get the
request and we'll remove this and search
for delivery options. And we'll click
one of these and then look at the
response tab. So, the backend responded
with three delivery options. Each
delivery option has the number of days
it takes to deliver and the price in
cents. However, if we open our website,
notice that each delivery option also
has a estimated delivery time. So, we
could use this delivery days to
calculate this date on the front end.
But remember, it's generally the
backend's job to manage the data and do
these calculations.
So, if we go back to our code,
this URL path also supports a query
parameter called expand. So at the end
we'll add question mark expand equals
and I called it estimated
delivery time.
So when the back end sees this expand
parameter it will calculate the
estimated delivery time for us and then
give it back in our response. If we save
and check the console
and refresh
and open the response and now you'll see
that each delivery option now has an
estimated delivery time in milliseconds.
So now we'll go back to our code and we
have what we need to display the date.
As you can see it's generally the
backend's job to manage the data and to
do the calculations. And now the front
end's job is to present that data in an
easy to read way on the website.
So now let's use these delivery options
to generate the HTML. We're going to
click in this file and press Ctrl+F to
search for code. And we'll search for
delivery dash options.
And inside here we should see an element
with a class name delivery option. So
we're going to collapse this element and
also collapse the other delivery options
and each of these represents one
delivery option on the page. So let's
generate this HTML using React. Above
this we'll insert and we'll run the code
delivery options dot map brackets and
give it a function brackets arrow and
curly brackets and the parameter will be
each delivery option
and here we're going to return brackets
some HTML for each delivery option. So
we want to return this HTML. So we can
select it and copy. And inside here
we'll paste.
And we can fix the formatting using
control or commandshiftp
and press format document.
And let's scroll up. And as always, we
need a key prop whenever we're looping
through an array. So we'll add key
equals curly brackets. And each delivery
option has a unique ID. So we'll just
set it to the delivery option
ID.
Next, we're going to replace these
values here. So first we'll do the
delivery date. Currently, we only have
the delivery time in milliseconds. So
how do we display it as a date like
this? To do that, we can use another npm
package called Dayjs.
So, we're going to go to the terminal
and go to the tab that's running our
front end. And we can press Ctrl C to
stop the server. And we're going to npm
install dayjs. And we'll type at to give
it a version. And we're going to click
this link in the description to get the
version of day.js we're going to use.
And we'll copy that version and paste it
in here and press enter to install
day.js.
And after that we're going to npm rundev
to restart the server.
So the dayjs package helps us work with
dates and it helps us display a date in
a particular format. To use it, we're
going to scroll to the top and at the
top we're going to import dayjs
from the package day js.
And now we'll scroll back down or we can
control F and search for delivery
options.
And we'll scroll down here. And now
above this date, we're going to insert.
And we're going to run day JS and
brackets. And we're going to give Day.js
DJs a time in milliseconds which we
actually have inside delivery option dot
estimated
delivery time ms or milliseconds.
And now that we wrapped this in dayjs we
can format it into this format. So after
this bracket here, we're going to use
the method dot format and brackets and
give it a string. To show the time in
this format, we're going to type D four
times,
which is the day of the week. And then
we'll type a comma to show this comma
and a space. And we'll type capital M
four times
to show the month and a space. and we'll
type capital D which will show this
date. And now we can remove this code.
Next, we're going to replace this price.
If the price is free, we'll show free
shipping. Otherwise, we're going to show
the price dash shipping. So, we're going
to scroll up to the inside of this loop
here,
and we're going to create a variable for
the price. So, we'll do let price string
equals a string. And to make it easier,
we're going to set this to a default of
free shipping.
And then we're going to overwrite this
if we have a price. So, below this,
we're going to check if brackets the
delivery option.
Sense is greater than zero.
curly brackets. So if it is not free,
we're going to overwrite this price
string equals a template string
and inside we're going to insert and
remember we have the format money
function to display the price. So as I
here we'll call format money and
brackets and we're going to give it the
delivery option price sets.
And at the end we're going to add a dash
and shipping.
And now we can scroll back down
and instead of free shipping every time
we're going to insert the price string.
Next, we're going to scroll up a bit and
there's a few things that we need to
replace for this input type radio
element. So, this represents the
selector and there's a few special
attributes that we need to replace. The
first one is the name attribute. So, the
name groups the selectors together. So,
each set of selectors should have a
unique name. This makes sure that for
each product we can only select one of
them. So here instead of doing delivery
option one every time we're going to
replace this with a product ID because
each set of selectors should belong to
one product.
So in this code we're going to replace
it using curly brackets
and change this to a template string
using a back tick and a back tick and
instead of one every time we're going to
insert and we'll insert the product ID.
Now in this code we actually have access
to the cart item from above. So inside
here we can just insert the cart item.
ID.
Next we also need to update this checked
property. So this determines if the
selector is checked. So we don't want
the selector to be checked every time.
Each cart item has a delivery option ID
and this is the one that should be
checked. So, inside here, we're going to
add a new line. And we're going to make
check equal and insert some code. And
we're going to compare if this delivery
option do ID is equal to the cart items.
Option ID.
So only the delivery option that matches
the delivery option ID in the cart will
be checked. So that's all the things
that we have to replace in the delivery
options. So now let's scroll down and we
can remove this default code
and save
and let's check the website.
And now we're generating these delivery
options and the correct ones are checked
and we have the estimated delivery dates
for each displayed in an easyto read
format.
The last thing we need to generate is
this delivery date up here. So, we'll go
back to the code
and we're going to scroll up
um to the cart item and we're going to
find the cart item container and this
delivery date here. So, this date is
determined by whichever delivery option
is selected. So, first we need to find
the delivery option that is selected.
So inside this loop, we'll create a
variable const for the selected
delivery option and equals.
And to find this, we're going to get the
delivery options and then use the method
dot find and brackets.
And find gets a function. So brackets,
arrow, and curly brackets.
And in this inner function, it receives
each delivery option. So we'll call it
delivery option.
And I'll just add a new line here and
select this code and press tab to format
it a little bit.
So the way that find works is it's going
to loop through each delivery option.
And the first function here that returns
true is going to be the result. So
that's how we find something. And then
it's going to save it in this variable.
So inside here we want to return the
delivery option id that is equal to the
cart items
dot delivery option id. So the delivery
option that matches what is inside the
cart item will return true and that's
going to be saved in here. And now we
can replace this date. So we'll type
curly brackets and we'll use day js
brackets and the selected
delivery option dot estimated delivery
time ms
and outside this bracket we'll use a
method dot format brackets and give it a
string and to get this date format we'll
give it d four times a comma and capital
M four times space and capital D.
And now we can remove this date here.
And before we run this code, there is
one small problem here because remember
the delivery options start out as empty.
So if they are empty, we might not find
the selected delivery option. To fix
this in front of this code, we're going
to check if delivery options.length
is greater than zero and type and and
as a review. This works like an if
statement. It will check if delivery
options.length is greater than zero and
then only if it's true, it will run the
rest of the code. So now we can save
and check the website.
And now we're generating everything here
using data from the back end. So let's
go back to our code
and we'll save this into git. Inside the
git section, we'll type the message
generate the HTML for the delivery
options
and commit.
Next, if we go back to the website,
we're going to generate the HTML for the
payment summary here. Now, we could
calculate all these numbers inside
React. However, we're going to use the
back end to calculate these numbers.
Remember, the backend's job is to manage
the data and to do the calculations. The
front end's job is to present the data
in an easy to read way. So let's go back
to our code and we'll go back to the
checkout page and we'll scroll to the
top and we're going to create a state
for the payment summary. So here we'll
type const square brackets equals use
state and brackets
and we'll name this payment summary,
and the updater function set payment
summary.
And as a starting value, we're going to
use null because the payment summary is
going to be an object. And it's a little
easier to check if the object is not
loaded if we set it to null at the
start.
Next, we're going to use Axios to get
the payment summary from the back end.
So down here, we'll use Axios.get get
brackets and we'll give it the URL path
slash API slash payment-
summary
and we'll use dot then to wait for a
response and give it a function
and inside here we can get the response.
Once we get the response, we're going to
use set payment summary brackets
response data to save the data inside
here. So now let's save and check the
response from the back end. So we'll go
to our website and open the console and
open the network tab and we'll refresh
just in case. We can click this to
remove the search and type payment
and we get the payment summary. So we
can click this and you can see that in
the response the back end calculated all
the numbers that we need. So now we just
need to present this on the page.
Let's go back and we'll press CtrlF in
this file and we'll search for payment
dash summary and press enter to find the
next result. And this section represents
the payment summary on the page. And now
we'll replace these numbers with the
numbers we got from the back end. So
first we'll replace the total quantity
here using curly brackets and we'll
replace it with payment summary dot
total items.
And here we'll replace the product cost.
I'll type a new line to make it a little
easier to read. And we'll insert.
And remember for money we need to format
it using the function format money
brackets. and we'll get the payment
summary dot product cost set.
We'll scroll down and we'll replace this
next number. So we'll remove it and new
line and curly brackets and we'll run
format money again brackets and this one
is a shipping cost which is payment
summary dot shipping cost sense.
Let's keep going. And this is the total
before tax. So we'll replace this and
insert format money brackets
payment summary dot total cost before
tax cents.
And we'll scroll down here and replace
this. insert format money brackets the
payment summary dot tax sets
and then down here we're going to
replace this one and insert format money
brackets the payment summary dot total
cost sense
and finally we only want to display this
if the payment summary is loaded
otherwise we don't have this
information. So above this code,
we're going to type curly brackets and
we'll check if payment summary and and
brackets.
So this checks if the payment summary
object exists. If it's null at the
start, it's not going to run the rest of
the code. And now we're going to put all
of this code inside here. So we'll
select all this code
up to the place order button and we'll
cut
and inside here we're going to paste.
Now a problem here is that we're
returning multiple elements inside this
brackets. So to fix that we need to wrap
this in a fragment using less than
greater than and remove this for now.
And at the end
after the button we'll do less than
slashgreater than. So we're returning
one element inside this brackets. And
now we'll format our code using control
or commandshiftp
and run format document
and save.
And that's it. Now we're generating the
payment summary using data from the back
end. We'll go to our website. And that
looks good. So now let's go back to our
code and we'll save this into git. In
the git section, we're going to type the
message generate HTML for the payment
summary and commit.
Next, we're going to work on the orders
page. So, we'll go back to our files
and we're going to open the orders page.
So, first of all, the orders page has a
header component. And remember, the
header now needs the cart in order to
display the quantity. So, we need to
share the cart with the orders page
first. We'll go to our files and open
app.jsx.
And we'll scroll down. And here we'll
share the cart with the orders page
using a prop cart equals curly brackets.
And we'll save the cart and save.
And now we'll open the orders page
again. And at the top we're going to
access the prop using curly brackets and
cart. And we're going to pass this cart
into the header using cart equals curly
brackets and the cart.
Let's save.
and we'll open the website and we're
going to go to the orders page. So,
first we'll click here to go to the
homepage and then we'll click here to
open the orders page and it should be
working. So, now we're going to generate
this HTML using data from the back end.
So, we'll go back to the orders page and
at the top we're going to import what we
need. So first we'll import axios from
Axios and we'll also import curly
brackets use state and use effect from
react.
And now down here first we'll create
some state to save the orders using
const square brackets equals use state
and brackets.
And we'll call this data the orders,
comma, and the updater function set
orders.
And at the start, we'll set the orders
to an empty array. And below this, we're
going to make a request to the back end
using use effect brackets and a function
brackets arrow and curly brackets. And
down here, we'll give it a empty array
so that it only runs once. And inside
we're going to use axios.get
again. So brackets and the URL path for
the orders is slappi/ord
orders
and then we'll do dot then to wait for
the response from the back end. We'll
give this a function brackets arrow and
curly brackets. Inside this parameter is
the response from the back end. And once
we get the response, we're going to save
it inside orders using set orders
brackets
response
data. Let's save.
And now we can check the network tab to
see if we got the orders. We'll open the
console.
Inside the network tab, we can refresh
and remove this and search for orders.
And down here, we'll click this request
and go to the response tab. And the back
end gave us the orders that we need to
display. Now, a problem here is that we
only have the product ID in the order,
but we also need to display some product
details on the website. And again, the
backend supports an expand parameter for
this URL path. So at the end here, we'll
add question mark expand equals
products. This time, make sure you have
an s at the end. So now let's save
and check the network tab again. And
we'll refresh.
And now inside the orders request,
you'll see that each order has the
product ID, but it also has the other
data for the product. And this is what
we need to display on the website.
So now we'll go into our code and we're
going to generate the HTML. So first
we'll press control or command F and
we're going to search for order dash
container
which is down here. And we can collapse
this code and collapse the other order
container. Each of these represents an
order on the website. So, we're going to
generate this HTML.
At the top, we'll insert and we'll run
orders.m map brackets. And we'll give it
a function.
And this parameter is going to be each
order.
And for each order, we're going to
return some HTML.
So, we want each order to be converted
into this HTML. We're going to select it
and copy it inside here. We'll paste.
Press control or command shiftp and run
format document.
And we'll scroll back up.
As always, we need a key prop when we're
looping through an array. We'll set the
key equals. And each order has an order
ID property.
As usual, we're going to replace the
values in here. Feel free to pause if
you want to try it yourself first. So
for the delivery date, we're going to
insert and we're going to use dayjs
brackets and each order has an order dot
order time ms
and outside this bracket we use dot
format brackets and a string. And to
display the date, we're going to use
four capital M's for the month and a
capital D for the date. So now we also
need to import day.js. So we'll scroll
to the top and at the top we'll import
dayjs from a string dayjs.
And let's also import format money
because we're going to use it later. So,
import curly brackets format money from
a string dot dot slashyouutills/
money.
Now, we're going to scroll back down
and we're going to replace the total
order cost. So here we're going to
remove this and curly brackets we're
going to insert format money brackets
and give it the order dot total cost
sense.
We'll scroll down and here we're going
to replace this with the order ID. So
curly brackets order ID.
Next, inside this element order details
grid. This displays the list of products
in the order and we're going to generate
this using React as well. So above this
we're going to use curly brackets and
we're going to get the order products
array and we're going to loop through it
using map brackets and give it a
function
and save each product
and for each product we're going to
return brackets some HTML.
So if we collapse this code and collapse
this element and this element and we
also collapse these.
So three of these elements represents
one product. It's a little different
because we don't have an element that
contains all of these because we're
using a grid here, but it works in a
similar way. We're going to copy this
code and inside return we're going to
paste
and the one difference here is that if
we scroll up
we're returning multiple elements from
this function. So we need to wrap these
in a fragment. So at the top we'll type
less than greater than. But then we have
another problem here which is remember
when we loop through an array each
element that we return should have a key
property and we can't add props to
fragments like this. To solve this we
need to use the full fragment syntax. So
we're going to scroll to the top and for
React we're going to import using comma
the fragment component.
So we'll scroll back down and in here
we're going to use a full fragment
syntax
and remove this. So this does the same
thing except now we can add a key prop
to it equals curly brackets and let's
set the prop to the product ID.
and we'll scroll to the bottom.
And before these brackets, remember to
add the closing fragment tag.
And finally, we'll press control or
commandshiftp
and format document.
And now we can replace this default code
that we have down here.
Finally, we're going to replace each
product's details. So here we're going
to replace the name and insert the
product name. And here let's also
replace the image
curly brackets. Replace it with product.
And actually I made a mistake. I forgot
that all the product details are saved
in a property called product. So let's
actually rename this to order product.
And then here we're going to do the
order product dotproduct ID and the
order product.product.im
image and the order
product.product.name.
And then down here to replace the
delivery date. This is directly on the
order product. So we can remove this and
insert and we'll use dayjs and bracket
and give it the order product dot
estimated delivery time ms and outside
these brackets we'll do dot format
brackets and a string and we'll use the
format capital M four times for the
month and capital D for the date. And
then down here for the quantity, we're
going to insert and the quantity is
directly on the order product dot
quantity
and save.
And now if we scroll down, we can also
remove the rest of this default HTML
and save this file. And now let's check
our website.
And everything should be working except
we're generating the HTML for these
orders using data from the back end. So
now let's go back and we'll save this
into git. We'll open the git section
and we'll give it the message generate
the HTML for the orders page and commit.
Next, if we look at our code right now,
you'll notice we have a lot of code in
one file. To make our code cleaner, we
should separate our code into smaller
components. So, let's go to our files
and we're going to start with the
homepage.
So, inside the homepage, we're showing a
grid of products. To make the code
cleaner, we can separate this into its
own component. So, we'll go to the pages
folder and we'll click it and we're
going to create a new file and let's
call it the products grid.jsx.
And now we have multiple components that
are related to the homepage. So, usually
we organize this into a folder. So,
inside here, we're going to create a new
folder and we're going to call it home
and press enter.
And we group all the components related
to the homepage inside here. So, we'll
move the homepage.jsx.
And let's update the imports
and also homepage.css
and also the products grid.
And whenever we move files, we need to
make sure the imports are still correct.
So in homepage, I'm going to scroll up
and we should make sure that we have two
dot dot slashes in front because now
we're inside an additional folder. So
that looks good to me. And we're also
going to go to app.jsx
and scroll up and make sure that the
homepage is now inside the home folder.
So now let's save and check our website
and go to the homepage to make sure it
still works. So now let's go back to our
code and we're going to separate the
products grid into its own file. So in
here we'll create the component using
export function
products grid brackets and curly
brackets and we'll return some HTML
and we're just going to copy the HTML to
here. So, inside the homepage, we're
going to scroll down to the products
grid and we can collapse this element
and select all this code and copy
inside the products grid. Inside here,
we can paste
and press control or commandshiftp and
format document.
Now, we'll scroll up and we're going to
fix these errors. So first we need
access to the products. So we can pass
those in as a prop curly brackets
products.
And down here we also need the format
money function. So at the top we're
going to import curly brackets format
money
from a string and we'll find that utils
file. So we need to get out of two
folders this time using dot dot slash
dot dot slash utils/money
and save.
And now inside the homepage at the top
we're going to import our products grid.
So import curly brackets
the products grid
from a string and it's right beside the
homepage. So we can just do dot slash
products grid.
And then down here we can remove this
HTML
and just use our component less than
products grid slashgreater than and we
need to give it the products. So we'll
create a prop products equals curly
brackets and we'll give it the products.
So, as you can see, this makes the code
much cleaner when we separate it into
smaller components. The last step is at
the top, we can remove this format money
function since we're not using it
anymore. Let's save
and let's open the website and make sure
everything still works. So, that looks
good.
Next, we're going to do the checkout
page. So, we'll go back to our code
and we're going to open the checkout
page and we're going to scroll to the
top.
And I'll leave separating the checkout
header as an exercise. But we're going
to scroll down here and we can move the
order summary section into its own
component. So, inside the pages folder,
I'm going to click it and create a new
folder called checkout.
Now, you might have already done this if
you did the exercises from the previous
lesson, but we're going to use this
folder checkout. And I'm going to move
the checkout page inside here.
And update the imports and also move the
CSS files.
And I'll make sure that the imports look
good. So, in here at the top, make sure
there's two dot dot slashes in front.
And inside app.jsx,
make sure that there is a checkout
folder in front of this component. So
I'll go back to the checkout page and
I'll create a new file. Let's call it
the order summary.jsx.
And we're going to create export
function order summary brackets and
curly brackets. and we're going to
return brackets the HTML for the order
summary. Inside the checkout page, we're
going to scroll down
and find the order summary. We can
collapse it and select this code and
copy.
Inside the order summary, we'll paste
and press control or command shift P and
format document.
and we'll scroll to the top and we're
going to need the delivery options and
the cart inside here. So, we're going to
get this from the props using curly
brackets, the cart, comma, and the
delivery options.
And we also need dayjs and the format
money function. So at the top we'll also
import dayjs
from day js and import curly brackets
format money
from a string
and we'll find the utils file which is
dot dot slash dot dot slash utils
slashmoney
and all the errors should now be gone.
We'll save.
And inside checkout page, we can remove
this code.
And we can use our new component less
than order summary /grater than. And we
need to give it the cart equals curly
brackets and save the cart. And we need
to give it the delivery options equals
curly brackets. And give it the delivery
options. And we need to import this at
the top. So we'll scroll up and here we
can import curly brackets the order
summary
from a string dot slash order summary.
And we don't need dayjs anymore.
So let's save
and check the website. And everything
still works.
We'll go back
and scroll down.
And next, we can also move the payment
summary into its own component. Feel
free to pause the video if you want to
try it yourself first. So, inside the
checkout folder, we'll click here and
create a new file, payment summary.jsx,
and we'll create the component export
function payment summary brackets and
curly brackets. and we'll return the
HTML.
Inside the checkout page, we're going to
collapse this element and select the
HTML and copy
inside the payment summary. We're going
to paste
control or command shiftp format
document
and we're going to scroll back up and
we're going to get the payment summary
from the props. So curly brackets
payment summary and we need the format
money function. So up here import curly
brackets format money from a string dot
dot slash dot do/youutils/money
and save.
In the checkout page, we can remove this
code and replace it with less than
payment summary slashgreater than. And
we need to give this the payment summary
equals curly brackets and save the
payment summary.
And as you can see, our code is much
cleaner now because we separated it into
smaller components. So now we need to
import this. So, we're going to scroll
to the top and here we'll import curly
brackets the payment summary
from a string dot slashpayment
summary.
And we don't need format money anymore
and save.
Let's go back to the website and
everything is still working.
We'll go back to our code
and we're going to go inside the order
summary component.
So in here the code is still a little
bit too complicated. So what we can do
is we can find this element with the
class delivery options and we can
separate this into its own component as
well. Feel free to pause the video if
you want to try this yourself first. So,
I'm going to go to the checkout folder
and create a new file and name it
delivery options.jsx.
And we'll create a component export
function delivery options brackets and
curly brackets and return some HTML. And
back to the order summary. And here we
can collapse this element and select it
and copy.
Inside delivery options inside here we
can paste. Control or command shiftp and
format document.
And we'll scroll to the top. Here we
need to get the delivery options using
the props. So curly brackets delivery
options.
And we're going to import format money.
So up here we're going to import curly
brackets format money from a string dot
dot slash dot dot slash utils/money
and we also need dayjs. So up here we'll
import dayjs from a string dayjs
and I think we also need another thing
here which is the cart item. So we're
going to get this from the props as
well.
So up here we're also going to get the
cart item and save.
And now in the order summary we can
replace all this code with our component
less than delivery options /grater than.
And we're going to give it the cart item
equals curly brackets. save the cart
item and give it the delivery options
equals curly brackets save the delivery
options
and we also need to import this. So at
the top
we can import curly brackets the
delivery options
from a string
dot slash delivery options
and save
and let's check our website and make
sure it still works. So that looks good
to me. So if we go back to our code, you
can see that our code is cleaner now
after we separate this into another
component. And remember, it's up to us
how we want to separate our components.
We can actually keep separating this
into smaller components if we want. For
example, we can also have a cart item
details component or a delivery date
component, but I'll leave these as
exercises. I'm also going to leave the
orders page as an exercise, but we can
just get started on it. So, here inside
the pages folder, we're going to create
a new folder for the orders page. So,
orders
and we're going to move this component
inside here
and update the imports.
And we're going to move this inside here
as well. And just make sure the imports
look okay. So in here, we'll scroll up.
Make sure that these two have two dot
dot slashes in front. That looks good.
And in app.jsx,
make sure that the orders page is now
inside an orders folder. So we'll save
this and open the website.
And we're going to click here to go to
home and click here to go to orders. And
the orders page should still be working.
So I'll leave separating this as an
exercise. We'll go back to our code and
we'll save this into git. Inside the git
section, we'll create the message
separate into smaller components and
commit.
Next, we're going to go back to our
files and we're going to go to our
homepage.
and we're going to review async await.
Async await is a feature of JavaScript
and it lets us write asynchronous code
like normal code. Right now we're using
promises which means we need to use to
wait for this code to finish and then
run this function with async await. We
can actually write this like normal
code. To do that in front of axios we
can type await and space. So this is
going to wait for this code to finish
and then it's going to move on to the
next line. And now because we're waiting
for this code to finish, we can actually
save this result in a variable. So at
the front we can save it in const
response equals await this code.
And now we don't need to use dot then
anymore
and we can remove it.
However, in order to use a weight, we
need to be inside an async function. So
in front of this function, we need to
add async and space. As you can see,
async8 lets us write asynchronous code
like normal code or code that runs line
by line. And async await makes the code
easier to understand. So in react it's
recommended to use async await instead
of promises when we can. However, in
React there is a small problem with
using async await and use effect. As a
review, when we put async in front of a
function, this function will now return
a promise. That's because this function
has some asynchronous code inside or
code that takes some time to finish. So
that means that this entire function is
going to take some time to finish.
That's why it has to return a promise.
Now the problem is the inner function in
use effect should not return a promise.
It should only return nothing or a
cleanup function like this. A cleanup
function is useful if we want to do some
cleanup when this component is removed.
So because this inner function is now
returning a promise, it's sort of
breaking the rules of use effect. To
solve this, we usually create a new
function inside use effect like const
get home data equals and create a new
function brackets arrow and curly
brackets. And we're going to make this
function async. And we'll leave this as
an ordinary function.
And now we're going to move our code
inside here. So we'll cut it and paste
it. And now because we're inside an
async function, we can now use a weight
and it will also not mess up use effect.
At the end, we just need to run this
function using get home data and
brackets.
So this gets the same data as before but
it uses async await. So remember when
using async await inside use effect we
need to create a new function and then
run the function otherwise it will break
the rules of use effect. So let's save
and check the homepage
and go to the homepage and everything
still works. So let's go back
and we'll use async await in the app
component
where we get the cart. So here feel free
to pause if you want to try yourself
first. We'll create a new function using
const. Let's call it fetch app data
equals a function brackets arrow and
curly brackets.
And we'll move this code into the
function. So we'll cut and paste and
we'll select this and press tab.
In front of the function we'll use
async. And now we can use await inside.
So in front of axios we'll type await to
wait for this to finish. And then we're
going to save the result in a variable
const response equals this result.
And now we can remove
and these brackets
and the code is much cleaner. Finally,
we're going to run this function fetch
app data and brackets and save.
And let's do the same thing in the
checkout page. So we'll go to the
checkout page here.
Feel free to pause if you want to try it
yourself. const fetch checkout data
equals brackets arrow and curly brackets
and we'll move this code inside cut
and in here paste and select these lines
and press tab and we're going to turn
this into an async function so we can
use await inside. So in front of this
request, we're going to await.
And we're going to save it in a variable
let response
equals. So we're going to use let
because we have two requests here and we
might want to reuse this variable. And
I'll add a new line to make it a little
easier to read. And now we can remove.
And then down here, we'll also use await
to wait for this to finish. And we're
going to save the result inside response
equals.
And now we can remove then.
And the last step is to run this
function. So fetch checkout data and
brackets and save.
We'll open the website. Make sure the
homepage is working and then go to the
checkout page and make sure this is
still working. So that looks good to me.
We'll go back to our code
and that's async await. It lets us write
asynchronous code like normal code. I'll
leave converting the orders page to
async aait as an exercise. So now we can
save this into git.
We'll give it the message convert home
and checkout
to async await and commit.
In the next lesson, we're going to learn
data mutation, which means instead of
just getting data from the back end,
we'll update data in the back end, and
we'll be able to add products to our
cart and create orders. And that's the
end of this lesson. In this lesson, we
reviewed backend, which manages the data
for a website. We set up a backend for
our project. We learned how to fetch
data or get data from the back end. We
learned Axios, which is an easier way to
make requests to the back end. We
learned how to generate the HTML using
the data from the back end. We separated
our pages into smaller components and we
learned async a weight which lets us
write asynchronous code like normal
code. Here are some exercises to help
you practice what we learned in this
lesson.
In this lesson, we're going to learn
data mutation and we're going to make
the website interactive. Data mutation
means we update data in the back end. If
we open the website
and I'll close some of these other tabs.
If we go to the homepage,
notice that right now we can only view
the data. If we try to update this data,
like we try to add to cart, it doesn't
do anything. So, we're going to make
this add to cart button work. We'll go
to our code
and we're going to find the add to cart
button. So, I'll open my files and I'm
going to go to the homepage and we're
going to open the products grid.
And we're going to scroll down in this
file to this add to cart button. The
first step is to make this button
interactive. So at the end we're going
to add an on click attribute equals
curly brackets and give this a function
brackets arrow and curly brackets.
As a review on click is called an event
handler. When we click this button it
will run this function.
Now, inside here, we're going to add the
product to the cart. So, we could try to
update the cart here in React, but then
we have to figure out where to save the
cart. Instead, in the real world, we use
the backend to update the cart and to
save the cart. The advantage of using
the backend is it will simplify our
React code and we can share the data in
the back end. So if we access this
website from another computer, we can
access the updated cart using the back
end.
So here to use a backend to add a
product to the cart. We're just going to
make another request to the back end.
We're going to go to the top
and at the top we're going to import
axios so that we can make another
request.
and we'll scroll back down.
And when we click this button, we're
going to make a request to the back end
using axios. And this time we're going
to use post and brackets.
So previously we used axios.get
to get data from the backend. Post is a
different type of request.
Is used to create data in the back end.
In this case, we are adding a product to
the back end. So, we're creating a new
cart item. That's why we use post.
Inside here, we're going to give it a
URL path slash API/cart-
items. So, notice this is the same URL
path that we used to get the cart. But
when we use post, the backend will
behave differently. This will create a
cart item instead of getting the cart
items.
Next, we need to tell the backend which
product to add to the cart. To do that,
we can give axios.post another value
which is an object.
When we use post, we can also send
information to the back end using an
object. And this is called the request
body. Now the back end needs to know two
things in order to add a product to the
cart. First, it needs to know the
product ID that we want to add. In this
case, this button is for if we scroll
up, the button is for this product right
here. So, at the bottom,
we're going to tell the back end we want
to add this product
ID to the cart. And we also need another
information which is the quantity that
we want to add. For now, let's just use
the quantity one. So this code will send
a request to the back end telling it to
add this product to the cart with a
quantity of one.
So now let's save this file
and then we'll go to the website
and we're going to go to this t-shirt
product and we're going to click add to
cart.
And then we're going to refresh the
page.
And now if we look at the cart here, we
have one more product. The quantity is
four. If we open the cart and we scroll
to the bottom, notice that it added the
t-shirt to the cart. So that's how we do
data mutation or update data in the back
end. We just send a request to the back
end and the backend takes care of
updating and saving the data. So, in the
real world, we use the back end to
manage and update the data.
Next, notice that when we added this
product to the cart, we had to refresh
the page to see the new cart. It would
be better if we could just reload the
cart and update the page without needing
to refresh.
We'll go to our code
and at the bottom, we're going to go to
app.jsx.
So here this code reloads the cart from
the back end and it updates the state.
After it updates the state, React will
update the page. So when we add a
product to the cart, we just need to
rerun this code and it will update the
page and then we don't have to refresh
the page every time.
We're going to select this entire
function and we'll cut.
And outside the use effect, we're going
to paste it.
And now that it's outside the use
effect, we can share this function with
our components.
Now, let's actually rename this function
to something more accurate like load
cart. And in here, load cart.
And now we can share this with our
components using a prop. So we're going
to scroll down here and in the homepage
we're going to give it the prop load
cart equals curly brackets and we'll
give it the function load cart and save.
And now if we go to the homepage
at the top, we'll get load cart out of
the props and then give it to the
products grid component. So remember
this component contains the add to cart
button. So in here we'll give it another
prop load cart equals curly brackets and
give it the load cart function and save.
And now inside the products grid
at the top, we're going to get load cart
out of the props. And then if we scroll
back down,
after we update the cart, we're going to
call the function load cart.
So this means we will update the cart in
the back end and then we'll get the new
cart and update the page without needing
to refresh.
One other thing we have to do here is
remember axios.post
contacts the back end. So this is
asynchronous code. It does not finish
right away. That means we need to wait
for this code to finish before going on
to the next line. To wait for this to
finish at the front of this code we can
type await and space. And remember in
order to use await we need to be inside
an async function. So we'll add async.
And also this code is not inside a use
effect. So we can just use async
directly here like this.
After that load cart is also
asynchronous. So it's a good idea to
await this code as well to be
consistent. So now let's save
and we'll check the website.
And first we'll go back to the homepage.
And this time let's click add to cart on
this toaster. So we'll click add to
cart.
And now notice that the quantity here
updated to five without needing to
refresh. If we go to the cart and scroll
down,
it also updated the cart on the page
without needing to refresh.
We'll go back to the homepage
and we're going to make these quantity
selectors work. So, this lets us add
more than one product to the cart at a
time. We're going to go to our code,
and first we need to get the quantity in
the quantity selector. To do that, we're
going to use a controlled input. We
learned controlled inputs when creating
the text box in the chatbot project. So,
as a review, we'll scroll up
and we're going to create a state to
save the quantity. At the top, we're
going to import curly brackets use state
from React.
And in this component,
we're going to create a state const
bracket equals use state and brackets.
And we're going to name the state the
quantity,
comma, and the updater function set
quantity.
And we'll set the starting value of the
quantity to one.
Then we're going to scroll down and
we're going to find this select element.
So this element represents the selector
on the page and we're going to give this
two props. The first prop is the value
equals curly brackets and the value is
the quantity.
The second prop is on change equals
curly brackets. And we're going to give
this a function. So brackets, arrow and
curly brackets.
And whenever we use an event handler
like on click or on change, this
function gets a parameter called event.
So event contains details about the
event. In this case, the event will
contain the quantity that we selected,
which is one of these values. To get the
quantity that we selected, we can use
event.target.
value
and let's save the quantity was selected
in a variable at the front. We'll create
const quantity selected equals this
value.
Now one thing to be careful of is this
value is going to be one of these values
here and these are going to be a string.
So we need to convert it into a number.
To do that around this value, we're
going to use the code capital n number
open bracket and close bracket.
So this will convert the string here
into a number. So now that we have the
quantity that we selected, let's save it
into the state using set quantity
brackets
quantity selected.
So this is called a controlled input.
When we have a value and an onchange
property when we change the selector,
it's going to set the quantity in the
state and then the new state is going to
be set as the value and then it updates
the page. So we're basically putting
react in the middle of this process so
that we have access to the quantity that
we selected. And that's a review of how
controlled inputs work. And let's also
console.log log the quantity selected to
see if it works. So, we'll save
and we'll go to the website
and we're going to open the console with
rightclick inspect and the console. And
now on the website, we're going to click
the quantity selector here and we'll
select three.
And now inside the console, it displays
the quantity that we selected.
However, there is a problem here. Notice
on this website when we change one
quantity selector, it changes all of
them. So if I change this one here to
five, it changes all the quantities. So
let's fix this. We'll go back to the
code.
And if we scroll to the top,
this is happening because the state here
is outside of this loop. So that means
the state is shared across all the
products. That's why when we change one
selector, it changes all of them. To
solve this problem, we need to move this
state inside this loop so that each
product has its own quantity. So, we're
going to select this code and cut.
And inside this loop, we're going to
paste.
However, this code actually breaks the
rules of React hooks. We can only put
hooks at the top level of a component.
We should not put hooks inside a loop
like this. To fix this problem, we can
separate each product into its own
component.
So, inside the home folder, we're going
to create a new file and we'll name it
product.jsx.
And we'll create a component for each
product, which is export function
product brackets and curly brackets. And
we're going to return the HTML for each
product. Inside the products grid, we're
going to collapse this code. And this is
the code for each product. So, we'll
select it and copy.
And inside the product component, we're
going to paste
and then control or command shiftp
format document.
We'll scroll up
and we'll go back to the products grid.
And we also need to copy over the state.
So we're going to select this copy and
inside product at the top we're going to
paste.
And we'll fix these errors. So first we
need to import use state at the top. So
import curly brackets use state from
react
and the product we'll get it from the
props using curly brackets product.
Scroll down
we'll need the format money function as
well as axios and load cart. So first
we'll import curly brackets format money
from a string and we'll find dot dot
slash do/youutils/money.
At the top we're going to import axios
from axios
and we'll get the load cart function
from the props. So, comma load cart and
save.
So, now each product has a separate
state. It has its own quantity. And this
is no longer breaking the rules of hooks
because this state is at the top level
of this component.
We'll go back to the products grid.
And here we can remove this HTML and
just use our component less than product
/greater than and we need to give it the
product
equals product and also the load cart
function equals load cart
and we can remove this state and
remember when we loop through an array
we need to give it a key prop. So at the
front here we'll set a key equals curly
brackets and we'll set it to the product
id.
And finally we need to import this
component. So we'll scroll up and at the
top we'll import curly brackets the
product component from a string and it's
right beside this file. So, we'll do dot
slash product and we can remove these
because they're no longer being used and
save.
And since we have the key in this loop
here, we can also go into the product
and remove the key in here and save.
Now, let's open the website.
And if we change one of these selectors,
notice that each product can now have
its own quantity.
Now that we have this quantity, when we
add a product to the cart, let's use
this quantity. We'll go to our code
and we're going to go inside each
product and we're going to scroll down
to the add to cart button here. And
instead of adding a quantity of one
every time, we're going to add the
quantity that is saved in the state
above. So now let's save
and we'll try out this code. We'll open
the website and let's go to this plate
product and we're going to select a
quantity of three this time and we'll
click add to cart.
And notice that the cart updated and it
now has a quantity of eight, which is
three more than before. If we open the
cart
and we scroll to the bottom, we now have
three of these plates in the cart. So
now the quantity selector is working.
Let's go back to the homepage.
And this time, let's try adding a
product that already exists in the cart.
So, for the plate product, we're going
to select the quantity of three again,
and we're going to click add to cart.
Notice the cart quantity increased by
three. And if we open the cart and
scroll down, instead of adding a new
plate product, it just increased the
quantity by three for a total of six. So
if the product already exists in the
cart, the backend handles this situation
for us and just increases the quantity.
Remember the purpose of the backend is
to manage the data. By letting the
backend manage and update the data, we
can simplify our React code.
Let's go back to our code
and we're going to do some cleanup in
this component.
First, instead of doing quantity colon
quantity, we can use the shorthand
property syntax and just use the
quantity. It does the same thing as
before.
Next, instead of putting our event
handlers directly in the HTML like this,
we usually save this in a separate
function. So, let's select all this code
and copy.
And we're going to scroll up.
And at the top we're going to create a
function const add to cart equals and
we'll paste that code.
So we usually save the function
separately like this. And then we can
scroll down.
We can remove this code and just use the
function name add to cart. And this
makes the code easier to read. Next,
we'll scroll up to the quantity
selector. We can remove the console.log
and we'll move this into a separate
function as well. We'll select this code
and copy
and we'll scroll up
and here we're going to create another
function const select quantity and make
it equal and we'll paste that code and
we'll use this function below. So down
here,
instead of putting this function
directly in the HTML, we use the
function name select quantity and save.
And that's it. We created the add to
cart feature. In the final project,
there's a small message that pops up
when we click add to cart, but I'll
leave this as an exercise. Now, let's
save this into Git. We'll open the git
section and let's use the message create
add to cart feature and commit.
Before we continue, I want to go back to
the code that we wrote. So, we're going
to scroll up in this component and I
want to explain axios.post
a little more. As a review, when we send
a request to the backend, we can set a
URL path. Based on the URL path, the
backend can do different things. For
example, if we use / API/roucts,
the backend gives us the products. If we
use / API/cart items, the backend gives
us the cart.
In addition to the URL path, every
request also has a type. In the previous
lesson when we did axios.get/api/cart
items, this actually sends the type get
and the URL path/ API/cart items to the
back end. So it sends two pieces of
information to the back end. The type
and the URL path.
When we did axios.post/appi/cart
post/api/cart
items. This sends the type post and the
URL path /api/cart
items to the back end.
Now when the backend receives our
request, it looks at both the type and
the URL path to decide what to do.
For example, if the backend receives get
and/api/cart
items, it will get the cart items and
return it. If the backend receives post
and/appi/cart
items, it will create a new cart item.
So both the type and the URL path
together determine what the backend
does.
In the description, I have a
documentation page for my backend,
and it lists all the different requests
that my backend supports. Notice that
each request has a type and a URL path.
By the way, the type is also called a
HTTP method.
When working with a backend, there are
four common types of requests that we
use. Get, post, put, and delete. Get
means we want to get some data. Post
means we want to create some data. Put
means we want to update some data and
delete means we want to delete some
data.
So, Axios has a method for each type.
Axios.get Get sets the type of request
to get. Axios.post
sets the type to post. Axios.put sets
the type to put. And axios.delete
sets the type to delete. And then
between the brackets, we put the URL
path.
So in our code, this sends a request to
the back end with the type post and the
URL path/ API/cart items. So the most
important thing to remember here is that
each request has a type and a URL path
and both of these determine what the
backend will do.
In the rest of this lesson, we'll get
more practice sending different types of
requests to the backend.
Next, let's go back to the website.
And inside the checkout page for each
product, we have these delivery options.
So, we're going to add the ability to
update the delivery option. Because
we're updating something in the cart,
we're going to practice using a put
request.
First, let's find the code for these
delivery options. We'll go back to our
code
and open our files.
and we're going to find the pages and
checkout folder and we're going to open
delivery options.jsx
and we'll scroll down
and here each of these represents one
delivery option on the page. So we're
going to put an on click property on
this element. Now, usually we put the on
click on the input, but in this case,
this will make only the radial selector
clickable. Instead, we want the entire
delivery option, including the text, to
be clickable. So, that's why we're going
to put the on click on the outside
component.
So, we're going to add the on click
attribute equals curly brackets. And
let's create a function for this. Above
this, we'll create a function with const
and let's name it update delivery option
equals. And let's make it an async
function brackets arrow and curly
brackets because we know we're going to
make a request to the back end to update
the delivery option.
Also, we create the function here inside
of this loop because we need access to
each delivery option.
So next to update the delivery option
for a product, we're going to make a
request to the back end. We're going to
scroll to the top and at the top we'll
import axials from Axios
and we'll scroll back down
and inside here according to my
documentation my backend supports the
request put/ API/cart items. This lets
us update the cart. For example, we can
update the delivery option for a
product.
So, we're going to do axios.put
brackets.
This sends a request with the type put
to the back end. And we'll set the URL
path to / API/cart-ite
items. And we'll add another slash. And
we're going to insert the product ID
that we want to update here at the end
of the URL path. So in my documentation,
colon product ID is known as a URL
parameter. This means my backend wants
the product ID we want to update inside
the URL. This is just a naming
convention that is popular with
backends. When we update something, we
usually put the ID of what we want to
update inside the URL. So here first
we're going to change this to a template
string using back ticks
and then at the end we'll insert dollar
curly brackets and we're going to insert
the product ID that we want to update.
So the product ID is saved inside the
cart item. So inside here we're going to
insert the cart item
product ID.
Next, we need to tell the backend which
delivery option we want to update to. To
do that, we're going to give the backend
some data. At the end of this, we'll add
a comma and an object.
And in my documentation, this section
tells us what data we can send to the
back end. Here, we can send the delivery
option ID that we want to update to.
So, we're going to give the back end the
delivery option ID that we want to
update to. So, if we scroll up here, we
want to update to this delivery option.
So, we'll tell the backend to update to
the delivery option ID.
And after we update the delivery option,
we're going to reload the cart and
update the page.
So in front of this, let's wait for this
to finish using await.
And remember, we created a function for
reloading the cart called load cart. So
inside app.jsx,
we're going to share load cart with the
checkout page. So down here we'll add a
prop load cart equals curly brackets
load cart and save.
And then inside the checkout page
at the top we're going to get load cart.
And now we need to share this with the
delivery options. Now the delivery
options are actually inside the order
summary. So we're going to share it with
the order summary first.
We'll scroll down to the order summary
and here we're going to give it the load
cart equals curly brackets load cart and
save
inside the order summary
at the top we're going to get from the
props load cart and then we're going to
share it with the delivery options. So,
we'll scroll down to these delivery
options and we'll give it the prop load
cart equals curly brackets load cart and
save.
And finally, in the delivery options, we
can get load cart from the props. So,
comma load cart and scroll down.
After we update the delivery option,
we're going to await load cart and
brackets so that we reload the cart and
update the page and we don't have to
refresh to see the updates. Finally,
we're going to take this function and
put it in this on click. So, update
delivery option
and save.
Now let's go to the website
and we'll try changing a delivery
option.
And now you can see that it updates when
we change the delivery option.
Now one last thing here is if we open
the console,
we're going to get this warning message
saying we provided a check property
without an onchange handler. So let's
fix this warning. We're going to go back
to the code
and the warning means that for an input
element, if we have a checked prop, we
should also have an onchange prop. On
change lets us change the value of this
input.
However, in our situation, we already
use this on click up here to change the
value of the input. So, we don't really
need an onchange property. So in here to
get rid of that warning, we can just add
an on change property equals curly
brackets and give it an empty function.
And this will just make the warning go
away. We'll save
and go back to our website.
And let's refresh.
And now if we change the delivery option
and check the console, we no longer get
that warning.
Next, we have another problem on this
page, which is when we update the
delivery option. The payment summary
here is not updating to show the new
delivery price.
To fix this, after we update a delivery
option, we also want to reload the
payment summary. So, let's find the code
for reloading the payment summary. We'll
go to our code
and we're going to open the checkout
page
and we're going to scroll up
and inside this use effect we have this
code here that reloads the payment
summary.
So we want to rerun this code after
updating the delivery option. Now we
could separate this into a function and
then share it like we did with load
cart. However, we have an easier option
here. Remember that in use effect at the
end we have this dependency array. So
this array determines when use effect
runs. Right now it's empty which means
use effect will only run once. However,
we can put values inside this array. And
whenever a value changes, it will rerun
the use effect. In our situation, we can
put the value cart inside this
dependency array.
And now whenever the cart changes, it
will rerun the use effect and update the
payment summary. And that makes sense.
Every time the cart changes, we do want
to update the payment summary in case
the cost of the order changes.
So in React there are often multiple
solutions to do something and we should
try to pick the cleanest solution.
Also note that this will cause the
delivery options to be reloaded which is
not really necessary. So we could
separate reloading the payment summary
into another use effect but I'll leave
this as an exercise.
So now let's save
and we'll go to our website.
And now when we update the delivery
option, notice that the payment summary
also updates to show the new delivery
price. And now this feature is working.
So now let's save this into git. We'll
go back to our code and open the git
section.
And here we'll use a message create
update delivery option feature and
commit.
Next, we're going to go to our website
and we're going to work on deleting an
item from the cart. So, we're going to
practice making a delete request to the
back end. First, we're going to find the
code for this delete link. We'll go to
our code
and in our files we're going to find the
order summary component
and we're going to scroll down in this
component and find the delete link. If
you did the exercises, this might be
inside a cart item details component.
Now, for this delete link, we're going
to add an on click attribute equals
curly brackets. And we'll give this a
function to run. Let's call it delete
cart item. And let's create this
function above. So, I'm going to scroll
up
and I'm going to create the function
inside this loop because I need access
to this cart item to delete. So in here
we'll create the function const delete
cart item equals a function.
And let's make this an async function
because we know we're going to make a
request to the back end. And first let's
import axios. So we'll scroll up and at
the top we'll import axios from a string
axios.
And then inside this function,
my backend can receive a request called
delete/appi/cart
items. And this will delete a product
from the cart. So we'll do axials
dodelete
and brackets.
This sends a request with the type
delete to the back end. For the URL
path, we're going to use a template
string and we'll do / API/cart-
items slash and we're going to insert
the product ID in the URL. Again, this
is just a naming convention that my
backend uses. So, we're going to insert
the ID of what we want to delete. In
this case, we need to give the backend
the product ID we want to delete. So the
product ID is saved inside the cart
item. So we're going to give the backend
the cart item dot product ID. And that's
it. When my backend receives a request
with the type delete and this URL path,
it's going to delete this product from
the cart. So after deleting the product,
let's reload the cart. First, at the
front of this, we'll type await to wait
for this code to finish. And then we're
going to await load the cart and
brackets.
So, I have load cart already in the
order summary. If you did the exercises
from the previous lesson, you may need
to pass this function into your
component using a prop.
So, now let's scroll down. And that's
all we need to delete a product from the
cart and then reload and update the
page. Let's save.
We'll go to the website
and we're going to delete this first
product.
And notice it updates the cart and it
also updates the payment summary. If we
delete another product, you'll notice it
updates the cart and updates the payment
summary. So that's how we make the
delete link work. I'll leave updating
the quantity in the cart as an exercise.
So now let's save this into git. We'll
open the git section and then here we'll
use the message create delete cart item
feature and commit.
Let's go back to the website.
And in the checkout page, we're going to
add the ability to create an order. So,
first let's find the code for this place
order button. We'll go back to our code
and in our files,
we're going to open the payment summary
component and we're going to scroll down
to the bottom to this place order
button. And to this button, we're going
to add a prop on click equals curly
brackets. And we'll give it a function.
Let's call it create order.
And now let's scroll up and create this
function. So up here
we're going to create const and we'll
name it create order equals an async
function brackets arrow and curly
brackets.
Again we're going to make a request to
the back end to create the order. So at
the top we're going to import axios from
a string axios
and in here for my back end we can send
a request with the type post and the URL
path /api/orders
to create an order. So we'll use the
code axios.post post
to make a request with the type post and
then give it the URL path slash API/
orders.
And that's all we need. Remember the
cart is already saved in the back end.
So the back end can take that cart and
create an order for us.
So let's wait for this code to finish
using a wait.
And after we create an order, the back
end will remove everything from our
cart. So we also need to reload our cart
here. First we need to get the load cart
function and that can be found in the
checkout page.
So here we get load cart from the props
and we're going to share this with the
payment summary. So, we'll scroll down
and in the payment summary, we'll share
load cart using a prop load cart equals
curly brackets load cart and save.
And then inside the payment summary
at the top in the props, we'll get comma
load cart.
And now after we create an order, we're
going to await load cart and brackets to
reload the cart and update the page.
Finally, after we create an order, let's
also redirect to the orders page so we
can see our new order. To do that, React
Router provides a hook that lets us
navigate to another page or go to
another page. At the top, we're going to
import curly brackets use navigate
from React-Router.
And at the top of our component, we're
going to use const
equals use navigate and brackets.
So use navigate gives us a function and
this function lets us navigate to or go
to another page in our app. So after we
create an order and we reload the cart,
let's navigate to the orders page using
navigate brackets and a string. And
we're going to navigate to slash orders.
Now, navigate is not asynchronous, so it
finishes immediately and we don't need
to await this code. Let's save.
And we'll go to the website and test out
the place order button.
So, we could update the delivery option
to get a shipping cost. And then click
place order.
And now you can see that it created a
new order.
You'll also see that it updated the
cart. So, the quantity is now zero. And
it navigated us to the orders page.
Once we are on the orders page, there's
some code at the top of the orders page
that loads the orders from the back end
and updates the page. And that's how
we're able to see our newest order here.
So, that's how we create an order. I'll
leave making these add to cart buttons
work as an exercise.
So now we finished all the major
features of our project. We can add
products to our cart. We can update the
cart and we can create an order. And
you'll see that in the real world, we
use a backend to manage and update all
the data.
And in our React code, we just make
requests to the back end and then update
the page. The advantage of letting the
backend manage the data is that it will
simplify our code a lot. So now let's
save this into git. Go to the git
section and at the top we'll type make
create order button work and commit.
And now we finished all the major
features of our project. In the next
lesson, we'll learn how to create
automated tests in React to make sure
our code still works whenever we make
changes. And that's the end of this
lesson. In this lesson, we learned data
mutation, which means to update data in
the back end. We learned different types
of requests like get, post, put, and
delete. We sent a post request to add
products to the cart and to create an
order. We sent a put request to update
the cart. We sent a delete request to
delete a product from the cart. We used
the dependency array of use effect to
update the payment summary whenever the
cart changes. We learned the use
navigate hook which lets us navigate to
another page using our code.
Thanks for watching so far. If you find
this course valuable, you can support
the channel by liking this video,
leaving a comment, and subscribing.
You can also check out the premium
version of this course where you'll get
all the lessons ads free broken down
into small videos, as well as additional
lessons and more projects that are not
in the public React course. Currently,
the premium course contains 11 lessons,
and I'll be adding more lessons in the
future. You can also get a certificate
of completion, create comments or
questions on specific topics, get
progress tracking, search and course
notes. You can also check out the
membership where you can get this course
ads free separated by each lesson, AI
videos, backend tutorials, and more.
Thanks again, and let's continue with
the course. Here are some exercises to
help you practice what we learned in
this lesson.
In this lesson, we're going to add
automated tests to our app. Automated
tests means using code to test our app.
This is more efficient than manually
opening the app and clicking around to
test it.
To create automated tests in React,
we're going to use an npm package. The
two most popular packages for automated
testing are justest and vest.
We're going to use VEST because it
integrates well with Vit, but just and
Vest are very similar. If you learn one,
you can easily learn the other. First,
we're going to install Vest to our
project. So, we're going to go to our
command line and open the tab that's
running the front end. And we'll stop
the VIT server using C.
And we're going to npm install
dash save-dev
test.
So, save dev means that vest is only for
development. This package is not needed
to run our app or to run our website.
And we're also going to add at to give
vest a specific version. So you can
click this link in the description, go
to lesson 9, and here you'll find the
version of Vest that we'll install. So
we'll copy that version and then paste
it in here
and press enter to install VEST.
Now that we installed Vest, we're ready
to create our first automated test. So
there are different types of automated
tests that we can create. The first type
is called unit tests. A unit test means
we test one unit or one piece of the
code. For example, if we look at our
files
and we open our utils folder and open
money.js, JS.
If we test a function like format money,
this would be considered a unit test
because it's just one piece of the code.
However, if we test something like the
product component here, testing
components like this are not unit tests
because they use many different pieces
of code together.
So, we'll start by creating unit tests
for format money.
So, we're going to go to this money.js
file, and beside this file, we're going
to create a new file for the tests. And
we'll name it the same money, but this
time we'll end with test.js.
So, the naming convention is to put it
beside the original file and end it with
test.js.
Now inside this test file at the top
we'll import curly brackets
it
from a string v test.
So it lets us create a test and we'll
also import
the format
money function from a string and import
it from this file dot / money.
And now to create our first test, we're
going to use it and brackets and we'll
give this a string.
So this creates a test and the string
here is the name of the test. So this
describes what we are testing. So let's
give it a name like formats1
1999
cents as $119.99.
If we run format money with 19.99, it
should give us $119.99
as the result. So this name is
describing what we want to test and a
naming convention is to make this read
like English. For example, it formats 1
1999 as 19.99.
And then we're going to give this a
function brackets arrow and curly
brackets.
And in here we're going to test if
format money works correctly.
To do that, we're also going to import
expect from vest. So expect lets us
check if the result is correct. So in
here we're going to run expect and
brackets.
And in here we put the code that we want
to test. For example, let's put the code
format money brackets and 1 n99.
And then expect has different methods
that we can use to check this result.
One method is called dot to b and
brackets.
So in this second bracket we can put the
expected result of this code. So we said
that the expected result should be this
string here. So we'll give it
dollar19.99.
So this code tests if this value is
equal to this value. If they are equal,
this check has passed. If they are not
equal, this check has failed.
And then expect is going to send this
result to vest. and V test will display
a summary of what passed and what
failed.
So now let's run this test. We're going
to save this file
and then in our command line, we're
going to create a new tab for running
the tests.
And first we have to be inside the
e-commerce project folder. So we'll cd
ecommerce
dash project
and we're going to run npx
vest.
So v test is going to search our code
for all the files that end with test.js
and runs the tests inside and then it
displays the result in the command line.
So this tells us that our format money
test here has passed.
Now let's create another test for format
money. We'll go back to this test file
and to create another test, we're just
going to use it again
and a string. And remember that we had
some problems with money not showing two
decimals.
So let's test if it displays two
decimals
and give it a function.
And now inside here we can run expect
and brackets
format money brackets. And let's give it
a value that might not show two decimals
like 1 090.
And then we'll check if this is correct
using
2 tob and brackets and a string. And the
expected result of this code should be
dollar 10.90.
So we're going to check if this result
is equal to this result. If we save,
vest is actually watching our files for
changes. So when we save it will
automatically rerun our tests. And now
you can see we have two tests that
passed.
Next inside each test we can have
multiple checks. So in here let's add
another check using expect brackets.
And let's try format money brackets with
a different value like 100. So we expect
this to be dollar1.00.
So we'll do 2v brackets dollar 1.0
and save.
Now v test will rerun all of our tests.
And now you can see that both tests
still passed. So when we have multiple
checks like this, all of the checks have
to pass in order for this test to pass.
If one of these checks fails, the entire
test will fail and it will show up here.
So as a quick example, if I change this
and save,
one of these checks failed. So we can
see that this test has failed. So I'm
going to add it back and save.
Next, if we look at our file here,
notice that these tests are related to
the format money function. A best
practice is to group these tests
together. To do that, at the top, we're
also going to import describe
from vest. So, describe groups test
together. we call a group of tests a
test suite.
So above these tests, we're going to use
the code describe and brackets and we'll
give this a string
and this is the name of the test suite
or the group of tests. So these tests
are for the format money function and
we'll give it a function brackets arrow
and curly brackets
and we're going to move our test inside.
So we'll select it and cut and paste
and save
and everything still passes
and we can see the test suite name over
here. So test suites basically help us
keep our tests more organized. If we
want to test a different function inside
this file, we would create another test
suite and group our tests in there. So a
best practice is to always put our tests
inside a test suite, even if we only
have one test suite. So now let's save
this into git. We're going to go to the
get section
and let's use the message create unit
test for format
money and commit.
Next, we'll create another type of test
called an integration test. Integration
test means we test multiple units or
pieces of code working together.
For example, if we look at our files and
we open the product component,
testing a component would be considered
an integration test. Notice this uses
multiple pieces of code like the format
money function and the load cart
function.
So now let's create tests for this file.
Beside product.js,
we're going to create a new file
and we'll name it product.est.jsx.
So we end with JSX this time because
this will let us use component syntax in
this file like this.
So, first let's actually copy the
imports from our money test file because
we're going to be using these again. So,
we'll copy
and in here
we'll paste,
but this time we're going to import the
product component from the dot /rouct
file.
And first we're going to create a test
suite. So we use describe brackets and a
string. And we're going to be testing
the product component.
And give this a function.
And inside we'll create our first
integration test using it brackets and a
string.
And for components, the first thing we
can check is if the component is
displayed correctly. So for the product
component, we can check if the name is
correct, the image is correct and so on.
So we'll name this test it
displays the product details correctly.
And we'll give it a function.
And now inside here, how do we check if
this component displayed the details
correctly? So when testing a function,
we run the function and check the
result. When testing a component, we
render the component and check the
result. So render means to display the
component on the page. To render the
component in our test, we need to add
some more npm packages. So, we're going
to go to our command line and right now
vest is watching all of our files for
changes. So, we're going to stop vest
using C or you can press Q to quit.
And now we're going to click this link
in the description, go to lesson 9, and
we're going to install all of these npm
packages that we need. So, we're going
to select this and copy. And then in our
command line, we're going to paste this
command
and press enter to install all these
packages.
After installing, we also need to create
some config files to test our
components. So, we'll go to our files
and we'll scroll down and find
vit.config.js
and click it. And we're going to create
a new file and name this
vtest.config.js.
And we'll click this link in the
description and go to lesson 9. We're
going to copy this setup code. So we're
going to select this and copy.
And then in here we'll paste that code
and save.
And we're also going to create another
file beside this.
So here create a new file called setup
capital T tests.js.
And we'll click the link in the
description again and go to lesson 9.
And we're going to copy this code
and paste it in here
and save.
So that's just some setup that we need
to do. If we look at this config file,
you don't have to worry too much about
how this works. This is just some
standard setup. These two are required
for component tests or integration tests
to work. And this basically runs the
code inside this file before all of our
tests. So in this file we import just
DOM and this basically adds a bunch of
methods to expect that help us test
components.
Now that we have the setup, we're going
to go back to our test
and at the top we're going to import
curly brackets render
from the package at testing-
library/react.
So this renders or displays a component
in a fake web page specifically for
testing.
Inside our test, we're going to use the
render function and brackets
and we'll tell it to render the product
component using less than product
slashgreater than.
So next the product component has some
props. So we need to provide these props
in our test. So in here we're going to
add the prop product equals curly
brackets
and we're going to provide a sample
product to test with. To do that in our
files we're going to go to the starting
code folder and open the data folder and
open products.js.
And here we have a bunch of sample
products that we can use. So, let's just
select the first product and copy it.
And then in our test,
we're going to save the sample product
in a variable const product equals and
paste.
And we're going to take this product and
save it as the product prop.
Next, we also need to provide a load
cart function to this component. So in
our app, load cart actually contacts the
backend. However, in our tests, we
should not contact a real backend
because the backend might not be
available during tests. In our tests
might accidentally update real data. So
instead, a best practice is to mock this
function in our tests. Mock means to
create a fake version of this function.
To create a mock at the top, we're going
to import vi from vest.
And we'll scroll back down and we'll
create const load cart equals vi.fn. fn
and brackets.
So, vi.fn
basically creates a fake function that
doesn't do anything. So, this fake
function is called a mock and we're
going to give this mock to the
component. So, here we'll create a prop
load cart equals curly bracket and our
mock load cart. And this will prevent
our component from accidentally
contacting the back end in our tests.
And that's it. This will render the
product component on a fake web page. So
now, how do we check if this component
was displayed correctly? We can't see
the fake web page, but we can check it
using our code. To do that, we're going
to scroll up
and we'll also import the screen from
testing library/react.
So screen lets us check the screen or
the fake web page to see if everything
was rendered correctly
in our test. After we render the
component, we're going to use screen and
the method
get by text and brackets.
So this searches the screen or the fake
web page for an element with a specific
text. So we'll give it a string
and first let's check if the product
name is displayed correctly. So, we'll
scroll up and we're going to copy this
product name.
And then in here, we're going to paste.
And this will search the screen or the
fake web page for an element with this
text inside.
So, now we're going to check if this
element exists. That will tell us if we
displayed the correct product on the
page. To do that before this code, we'll
use expect and open bracket
and at the end a close bracket and we'll
use the method dot to be in the document
and brackets.
So this method is added by testing
library/jestdom
and this checks if this element exists
on the screen or on the fake web page.
So now let's save
and we'll run this test using vest in
the command line. We'll run npx v test.
And all of our tests passed.
Next, let's add some more checks to this
test. So, let's also check if the price
was displayed correctly. So, here we'll
add another expect brackets and we'll
use screen.get get by text
and a string and we're going to search
for the price on the screen. So for the
sample product, the price should be
dollar10.90.
So, we'll scroll down and search for
dollar 10.90 on the screen. And we
expect this dot to be in the document
and brackets
and save
and feed will rerun the test and tell us
that this passed.
Next, let's check if the product image
is correct.
So down here we'll use another expect
brackets
screen dot but this time we can't use
get by text because we're trying to find
an image. Instead we're going to add a
test ID to the image element. So in our
files we'll open the product component
and we're going to scroll down until we
find the product image here.
And for this element, we're going to add
an attribute data-
test id equals a string product dash
image. So this ID lets us find the image
element in our tests. We could also use
the class name to find this element, but
if we change our class name, it will
break the test. To avoid this, we
usually use an ID specifically for
testing like this. So now let's save.
And in our test, we'll use screen dot
get by test ID and brackets and a string
and the test ID product dash image. So
this will give us the image element in
the product component.
Now let's check if this image element
source attribute is equal to the
products image up here. So we'll select
this image and copy
and then down here
dot to have attribute
brackets and we'll check the source
attribute if it's equal to the string
and paste
the image from our sample product
and Save
V test will rerun our tests and
everything passed. So we know we're
displaying the correct image.
Next, let's check the ratings image and
the rating count. Feel free to pause if
you want to try it yourself first. So
first we'll do expect
open bracket the screen dot and we'll
check the ratings image first.
So, we'll go to the product component
and we're going to scroll down until we
find the image product rating stars and
we'll give this a data dash test id
equals
product rating stars image and save.
And let's just select this test ID and
copy.
And in our test,
we'll get by test ID brackets a string
and paste.
And we expect this dot to have attribute
brackets the source attribute equals a
string.
And we'll go back to the product
component.
And let's just copy the source attribute
here. So we'll select it and copy.
And inside our test we're going to
paste.
Now for our sample product we have a
rating of
4.5.
So that means we take 4.5 and multiply
it by 10. We're going to get the value
45.
And this is the rating image that should
be displayed on the page. So we'll save.
And v test tells us everything passed.
Finally, let's check the rating count.
So we'll expect brackets screen dot. And
this time we're looking for text. So we
can just use get by text brackets. And
for this sample product, the count is
87.
So we'll look for the string 87.
And we expect this to be in the document
and save.
Vest will rerun and everything passed.
So now we tested if the product
component displayed all the details
correctly. So let's save this into git.
We'll open the git section
and we'll use the message create
integration test for product component
and commit.
Next we're going to test user
interactions.
In the product component, we have an add
to cart button. We can also test
clicking this add to cart button to see
if it behaves correctly.
So in our test file, let's create a new
test using it brackets and a string. And
let's name it adds a product to the cart
and give it a function.
So first let's render the product
component again. So we'll scroll up
and let's just copy all of this code. So
we'll select it
to here and copy.
And then in our second test,
we're going to paste.
So this sets up the sample product and
the mock and then renders the product
component again. So now that we rendered
this, how do we click the add to cart
button in our test?
Earlier we installed a package called
testing library/ user event. This
package lets us simulate events like
clicking a button. So at the top of our
test, we're going to scroll up and we'll
import user event from the package at
testing- library/
user-event.
So this lets us simulate events like a
click.
So now we'll scroll back down to our
test
and first we need to set up user event
using const user equals user event dot
setup and brackets.
So now we can simulate events using
user.click.
So this simulates a click event and
inside the brackets we're going to tell
it which element to click. So we want it
to click the add to cart button. So
first we need to get the add to cart
button inside our test. We'll go to our
files
and in the product component,
let's scroll down to the add to cart
button and we're going to give this a
data dash test ID equals a string add to
cart button.
And let's select this test ID and copy
and save.
And then in the product test, we're
going to get the button using screen dot
get by test ID brackets
and a string and we'll paste the test
ID.
So this will get the add to cart button
from the screen.
So let's save it in a variable const add
to cart button
equals
and we're going to give this to
user.click
add to cart button.
Next when we click this button it takes
some time for the page to process the
click. So user.click takes some time to
finish. That means this is asynchronous
code and it returns a promise. To wait
for this to finish at the front, we're
going to use await.
And remember to use await we need to be
inside an async function. So above in
this function, we're going to make it
async.
And we'll scroll back down.
And now once we click the add to cart
button, this is going to make a request
to the back end using axios.post.
But remember in our tests we should not
contact a real backend because we might
accidentally update real data.
So earlier we mocked load cart and
replaced it with a fake function.
Now we're also going to mock axios. So
we can actually mock an entire npm
package. To do that at the top,
we're going to use the code vi
mock brackets
and the string axios.
So this mocks the entire axios package.
This means that when we are testing,
when we import from axios, we will get a
fake version of axios instead.
So when we click add to cart, it will
use the fake version of Axios and it
will do nothing. It will not contact the
back end. So now what should we test? We
can still test that our code ran
axios.post
and we can test if we gave axios.post
the correct values.
To do that at the top, we're also going
to import Axios from the package Axios.
And because of vi.mmock,
this is a fake version of Axios.
So now we can scroll back down
and after we click add to cart, we can
expect brackets axios.post. post.
If we give a mock to expect, we can
check if our code ran axios.post
and if we gave it the correct values
using the method dot to have been called
with and brackets.
So we expect our code to call axios.post
with /api/cart items. So in here we'll
check if the first value we gave it was
slappi/cart-
items
and we also expect our code to give
axios.post an object with a product ID
and a quantity.
So in here we can also check if we give
it an object with a product ID colon and
we're going to get the product ID of our
sample product. So here we'll select
this ID and copy
and scroll back down
and create a string and paste the ID
and we expect the quantity colon to be
one because we did not change the
quantity selector.
So this basically checks that when we
click add to cart does our code run
axios.post post and give it these
values. So even though mocks don't do
anything, we can still check if we
called them and we gave them the correct
values.
Next, we can also check if our code ran
load cart. So remember that load cart is
also a mock. So we can see if our code
ran load cart. So down here we can also
expect
load cart and we don't give load cart
any values. So we can just use dot2
have been called and brackets.
So this just checks if our code called
load cart and does not check what values
we gave it. So now let's save
and v test will run our code and
everything still passed. So that's how
we test user interactions. We create
some mocks and then we check if our code
ran the mock and gave it the correct
values. So now let's save this into git.
In the get section, we'll use a message
test clicking add to cart button
and commit.
Before we move on, we're going to do
some code cleanup. Notice that in each
of our tests, we have some setup code at
the top where we create some sample data
and mock load cart. So we can actually
share this setup code between our tests.
To do that, we can move these two
variables outside of this it function.
So we'll select this code
and cut.
And outside of this function, we'll
paste.
Now that these two variables are outside
of this function because of scope these
can be accessed anywhere inside this
outer describe function. So that means
it can be accessed in both tests. So in
the second test
we can just remove this setup code
because now it's shared between the two
tests up here.
Another recommendation is to recreate
shared variables before each test
because if one test modifies a variable,
that change is going to carry over into
the next test which can cause bugs.
So before each test, we're going to
recreate these variables.
To do that, we can use before capital E
each brackets. And we'll give this a
function brackets arrow and curly
brackets.
So before each runs some code before
each test
and also we need to import before each.
So at the top
we'll import before each from vest.
So we want to recreate these shared
variables before each test. So we're
going to do that in here. Inside we'll
use product equals
and let's just select this value and
cut.
And in here we'll paste.
And because we're modifying this
variable, we need to change from const
to let.
And we'll also recreate load cart in
before each. So here we'll do load cart
equals vi.fn
and brackets
and above we can remove this
and change this to a let.
So now before each test we're going to
recreate the setup code and we'll have a
fresh set of variables and this will
make our tests more consistent. So now
let's save.
V test will rerun our test and
everything still passes.
So before each is known as a test hook.
There are other test hooks that we can
use to help us do some setup or some
cleanup in our tests.
So now let's save this into git. In the
get section, we'll use the message use
before each to remove duplication
and commit.
So, we just learned how to create mocks
that don't do anything. Now, we're going
to learn how to mock the implementation.
Mock the implementation means we make
the mock do whatever we want. To do
this, we're going to test another
component. So in our file,
we're going to go to the homepage
component.
And here we're going to create a new
file
and name it homepage.est.jsx.
And let's just copy all the imports from
the product component test because we'll
use most of them. So we'll select this
and copy.
And in homepage.test
we're going to paste.
And this time we'll import homepage
from dot /home page.
And as always, we'll start by creating a
test suite with describe.
And we'll name this homepage
component
and a function.
And we'll create a test using it
brackets. And let's call it displays the
products correctly.
Brackets, arrow, and curly brackets.
And now let's render the homepage using
render bracket less than homepage
slashgreater than.
And the homepage requires two props cart
and load cart. So for the cart equals
curly brackets. We're not going to test
the cart right now. So we'll just set it
as an empty array.
And for load cart equals curly brackets
again we'll mock load cart. So above
this test
we'll create let node cart and we'll use
before each brackets
and a function brackets arrow and curly
brackets
and we'll set load cart equals a mock
function vi.fn Fn and brackets
and we're going to give this mock to the
homepage component.
Next, the homepage component is special.
If we open the homepage,
notice at the start, we load products
from the back end using
axios.get/appi/roucts.
Again, in our test, we should not
contact a real backend. So, we're going
to mock Axios.
So, here
at the top, we'll mock Axios using
vi.mmock
brackets and the package axios.
Now, this just makes axios.get do
nothing. However, in the homepage, we
actually need axios.get get to return
something because we're going to return
a response and the homepage is going to
use this response to display the
products. So here axios.get cannot just
do nothing. We need to mock the
implementation which means we're going
to make axio.get do whatever we want.
So in our test inside before each
we're going to do axials.get
dot mock implementation
and brackets
and we're going to give this a function
brackets arrow and curly brackets.
So this means that in our code whenever
we use axios.get get it's going to run
this fake function instead. So basically
we can make axios.get do whatever we
want. That's what mock implementation
means.
So remember we can give axios.get some
values. Those values are going to be
saved as parameters in here. So the
first value we give to axios.get is the
URL path. So in here our fake function
will also get the URL path.
Next inside our fake function let's
check if the URL path is equal to the
string /
products.
So for the URL path /api/proucts,
usually the backend returns all the
products in an array. But in our test,
we don't really need all the products.
So let's just return two products to
test with. So in here, we'll just return
two products. Now, whatever we return
from this fake function should match
what axios.get normally returns. So
axios.get
normally returns a response with a
property data. So in our test
this mock implementation should also
return an object with a property data.
And normally
response data is an array of products.
So in our test, our data property should
also be an array.
So basically in this fake function, we
should match what axios.get normally
returns. And this makes sure that the
rest of the code still works with our
mock.
So now in our test,
let's just return two products to test
with. to find two sample products. We
can go back to the starting code folder
and the data and the products.js.
And here, let's just collapse the first
two products and we'll select them and
copy.
And inside the homepage test,
we're going to paste.
So now in our test, axio.get get will
return these two products.
Now there's one more thing we need to do
which is remember that axios.get
normally returns a promise that we have
to await. So in our test we should also
return a promise. To make this return a
promise we can wrap this value in
promise.resolve like this. Or an easier
way to do this is to make this function
async.
So remember that async makes a function
return a promise.
Now axios.get will return exactly what
we want. And that's how we mock the
implementation which means we make the
mock do whatever we want.
Now let's run our tests to make sure
that this works. We'll save
and v test will rerun and we actually
got an error. So if we look at this
error and we scroll up
to the details of the error, you'll see
that we got this error here and it came
from React Router. And this happens
because if we look at our homepage
component,
remember that the homepage also contains
a header component. And if we open the
components folder and the header
component,
inside the header component, we have
these link components.
In order for a link components to work,
they need to be inside a router. In
main.jsx, JSX the entire app is inside a
router. So that's why link components
work normally but in our test our
homepage component is not inside any
router. So the link component doesn't
work and it creates an error. To fix
this we just need to put a router around
the homepage in our test. So, we'll go
back to our test
and first we'll scroll to the top and
we're going to import a router. So,
we'll import curly brackets and we're
going to import the memory router
from the package react-outer.
So, the memory router is specifically
for testing.
So we'll scroll down
and when we render the homepage, we're
going to put it inside a memory router.
So less than memory router
and we'll select the homepage and cut.
And in here we'll paste
and we'll fix the indenting.
And now if we save
the link components are inside a router.
And now our tests should pass.
Now let's check if the homepage
displayed the products correctly. So
after we render this homepage because we
mocked Axios to return these two sample
products, there should be two products
on the page. Let's add a test ID to
these elements so we can get them in our
test. In the product component,
we're going to scroll up to the top of
the HTML and we're going to find the
product container
and we're going to add the attribute
data- test id equals a string the
product dash container
and save.
And in our test,
we're going to look for the test ID
using screen.get
all by test ID and brackets and the test
ID product dash container.
So we use all here because we're going
to have multiple products on the page.
So we're going to get multiple product
container elements.
However, there's actually a problem
here.
When the homepage is first created, the
products are empty. So, there will not
be any products on the page. And we need
to wait for the homepage to run use
effect and load the products and then
update the state. So to wait for
homepage to finish loading in our test,
we're going to use a different method
called
find all by test ID.
So find does the same thing as get, but
it will wait until it finds this
element.
So this is useful when our component
needs to load something and we need to
wait for it to load. Now, because this
code is waiting until it finds these
elements, this code is asynchronous and
it returns a promise. So, we're going to
wait for this code to finish using a
wait. And again, to use a wait, we need
to be inside an async function.
So now this will wait until it finds
these product containers. And then let's
save these in a variable using const
product containers equals this result.
And now we can check this result to see
if it was displayed correctly. So down
here
let's check if we have two product
containers on the page. So we can expect
brackets the product containers.length
dot 2b
2.
So this gives us an array of elements
and we're just checking if the length is
equal to two. If we save,
v test will rerun. And now this test
passed. So we know we're displaying the
correct number of elements on the
homepage.
Next, we'll check inside each product
container to see if they have the
correct product name. Now, before we
used screen get by text to search for
some text on the page. However, this
searches the entire page. Here we want
to check specifically the first product
container to see if it has the correct
name. To do that we can use a feature
called within. So we'll scroll up
and here we're also going to import
within
from testing library/react.
And we'll scroll back down.
And within lets us find things within or
inside a specific element. So to find
things inside the first product
container, we're going to use within
brackets the product containers square
bracket zero.
This gives us the first product
container and we're going to search
inside this container. And then here
we're going to do dot get by text and
brackets.
And for the first container, we're going
to search for the first product name. If
we scroll up,
this is the first product name. So we'll
select it and copy.
And down here,
we're going to paste.
So again, this searches inside the first
product container for this text. And
I'll add a new line to make it a little
easier to read. And now we expect this
to exist. So here we'll type expect open
bracket
and just going to reformat this code a
little bit and at the end close bracket
and use
2B in the document and brackets.
Now let's save
and v test will tell us that this
passed. So, we know we're displaying the
correct product in the first product
container. Now, let's check the second
product container. We'll select this
code and copy.
And down here, paste.
And we'll change the zero to a one. This
gets us the second product container.
And we're going to get the second
product name. So up here, we're going to
select this name and copy
and scroll back down.
And here we're going to paste
and save
and the test passed. So now we know that
the second product container is
displaying the correct product. Now we
could check all the other details of the
product as an exercise. However, we
don't have to do it because remember
that all the product details have
already been tested in the product
component test.
So instead for the homepage component,
we focus on testing things that are
specific to the homepage such as
rendering multiple products and loading
products using Axios.
So that's how we test a more complicated
component like the homepage. We need to
mock the implementation of axios.get
and we may need to wrap the component
inside a router. I'll leave adding more
tests for the homepage as an exercise.
So now let's save to git. We'll open the
git section and we'll use the message
create integration test for home page
and commit.
So now whenever we make changes to our
code we can run these automated tests to
make sure that format money the product
component and the homepage are still
correct. Now, usually we create tests
for all of our components, but I'll
leave that as exercises.
In the next lesson, we'll learn
deploying, which means how to put our
React app on the internet.
And that's the end of this lesson. In
this lesson, we learned how to create
automated tests with VEST. We learned
how to create unit tests, which test one
piece of the code. We learned it,
expect, and describe, which lets us
create a test, check the results, and
group the tests together into a test
suite. We learned how to create
integration tests, which test multiple
pieces of code working together. We
learned how to test a component using
render and screen. We learned how to
create a mock, which is a fake version
of a function or a package. And we learn
how to mock the implementation, which
means we make a mock do whatever we
want.
Here are some exercises to help you
practice what we learned in this lesson.
In this lesson, we're going to learn
deploying, which means how to put a
React app on the internet. So, there are
many services we can use to deploy. In
this lesson, we're going to use AWS or
Amazon Web Services. AWS is the biggest
service for putting websites on the
internet. Most big tech companies use
AWS, so it's the most useful to learn
for your career.
So AWS stands for Amazon Web Services.
It's a collection of services that help
us put stuff on the internet. And AWS
has a free tier where we can use many of
their services for free using some
credits.
So, let's click this link in the
description. Go to lesson 10.
And here we have a link to AWS.
Now, before we begin, AWS might change
their website design in the future. If
you have any issues, please check this
AWS troubleshooting guide here.
Now, let's get started with AWS.
We'll click this link to open AWS.
And the free tier is free for new
accounts. So, we're going to create a
new AWS account. If you don't see this,
you can also click sign in
and then scroll down and click create a
new AWS account.
Before we continue, because AWS is the
biggest web service, it has to follow a
lot of security and compliance
regulations. So, even though it has a
free tier, it will ask you for a credit
card, billing address, and phone number
when signing up. If you're unable to
provide this information, please check
the AWS troubleshooting guide in the
description.
However, I still recommend at least
watching this tutorial to see how AWS
works since it's the most useful for
your career. So, here we'll enter our
email address for logging in. So, for
me, I'll use this email
and then we'll go through the rest of
the sign up process.
After signing up, it might take a few
minutes for the account to be activated.
So, we just need to give it a bit of
time.
Now that we created a new AWS account,
one thing to note is when signing into
AWS,
if you see an account ID and I am here,
we're going to click this sign in with
root email button.
And then here we can sign in with the
email and password we created earlier.
After signing in, you can see the
details of the free tier here or by
clicking here.
After we sign in, we're going to land on
this AWS dashboard. So, as I said, AWS
is a collection of services that help us
put stuff on the internet. So, here we
can see all the services that are part
of AWS. And there's a lot of services.
At the top in the search bar, we can
search for a service. So, we're going to
start with the most basic service called
EC2.
And click here to open it.
EC2 stands for Elastic Compute Cloud. It
basically lets us rent a computer from
AWS.
Earlier in the course, I mentioned that
many websites use a backend to manage
the data and the backend is another
computer on the internet. Now, we could
buy a physical computer ourselves and
use that as the back end, but then we
have to keep this computer running 24
hours a day and put it in our office
somewhere. So this is a lot of work and
what most companies do is they just rent
a computer from AWS and AWS will manage
the computer and keep it running 24
hours a day and this saves a lot of
work. So EC2 basically lets us rent a
computer from AWS. This is called
infrastructure as a service or IAS. This
means that AWS manages the
infrastructure or the computers for us.
So to rent a computer in here, we can
click the instances section and then
click launch instance. By the way, one
instance is one EC2 computer.
However, we're not going to use this
because there's still some problems with
this process. EC2 just gives us a
computer. We still need to install
NodeJS on this computer. We still need
to connect this computer to the
internet. And we need to upload our code
to this computer. So even though AWS
manages the computer, there's still a
lot of manual work we have to do. To
solve this problem, AWS provides another
service.
At the top, we're going to search for
elastic
beantock
and click here to open this service.
You can think of elastic beantock as a
layer on top of EC2. It uses EC2 to rent
a computer, but it also installs all the
software we need on this computer and it
connects the computer to the internet.
So, Elastic Beantock also does all the
software setup for us. All we have to do
is just upload our code to elastic
beantock and it will just work. This is
called a platform as a service or a
path. This manages the infrastructure
and the software for us. If you want to
learn more about these concepts, you can
check out my backend overview video in
the description.
Now that we have an overview of AWS and
some of the services we can use, let's
learn how to use Elastic Beantock. Now,
Amazon might change the design of these
pages in the future. If you run into any
issues, make sure to check the AWS
troubleshooting guide in the
description.
We're going to start by creating an
application. Or we can click here, click
environments,
and create environment.
And on this page, we're going to select
a web server environment. And we're
going to give a name to our application.
So let's just use e-commerce-
project-
react.
And we can use the default values for
this section. And we'll scroll down. And
for the platform section, we're going to
choose the technology we want to use
here. For us, we're going to use NodeJS.
And down here, we'll just use the sample
application. We can upload our own code
later.
And we'll scroll down. And here we'll
choose single instance. If you see free
tier allegible, pick that one.
Otherwise, just pick the single
instance.
And then here we'll click next.
And here we need to create a role. A
role gives elastic beantock permission
to use other services in AWS.
So in here, if you already have a role
for elastic beantock, you can use that.
Otherwise, we'll click create ro.
And we should be able to use the default
values that they set here. And we'll
click next.
And then click next.
And at the bottom, we'll click create
roll.
And then we'll go back to Elastic
Beantock. And we'll click this button to
refresh.
And we'll select the RO that we just
created.
For this one, we also need to create a
role. So, we'll click here.
And then we can also use the default
values that it gives. Click next
and next.
And at the bottom, create RO.
And we'll go back and refresh
and select the RO that we just created.
And we can keep this as blank. And we'll
click next.
For the networking and database
settings, we can just use the default
values here. So, we'll scroll down and
click next.
And for the instance settings, we're
going to scroll down and find the
section called capacity.
And down here, we're going to scroll
down
and we're going to find a section like
this called instance types. And it has a
drop down here. So, this lets us choose
the size of the computer that we want to
rent from EC2.
So, in the description, we're going to
click this link and go to lesson 10 and
then follow the instructions here to
select the correct instance types.
So, now we'll scroll down and click next
and we can leave monitoring and logging
settings as the default. So, we'll
scroll down
and click next.
And finally, we'll scroll to the bottom
and click create.
So now, Elastic Beantock is going to
rent a computer for us using EC2. It
will also install all the software that
we need on this computer like NodeJS and
npm. And it will do all the
configuration to connect this computer
to the internet.
So, this will take a few minutes to
complete. So, we need to wait for this
to finish.
And you might need to refresh the page
to check the progress.
Once that's done, it should look
something like this. And we can click
this URL here or click here to open this
website.
And now we should see a sample NodeJS
application on this page. If something
goes wrong and this doesn't work, please
check the AWS troubleshooting guide in
the description.
Now that we set up Elastic Beantock,
we're ready to put our code on the
internet. We'll go back to Elastic
Beantock.
And our code has two parts, the back end
and the front end. We put the back end
on the internet first and then we put
the front end. To put the back end on
the internet, we just need to upload our
backend code to elastic beantock. So
we'll click upload and deploy.
And here we're going to upload our
backend code. However, we need to upload
the code as a zip file. So we'll go back
to VS Code.
And I'll collapse this for now. And I
actually set up the e-commerce backend
so that it works with elastic beantock.
So this backend has a command that will
save all the code in a zip file. So
we're going to go to the command line
and we're going to create a new tab.
And in here we're going to cd into
e-commerce backend.
and we'll run the command npm run zip.
So this will save all the backend code
into a zip file which is right here. If
I open this zip file,
you'll see that it just contains all of
the backend code.
So now we just need to upload this zip
file to Elastic Beantock. We'll go back
to the browser
and we'll click this to choose a file.
And for me, my code is on the desktop
inside the React course folder inside
e-commerce backend.
And if I scroll down, I'll see this
e-commerce backend one, which is a zip
file. So, I'll click this and open.
Wait for it to upload and then click
deploy.
So now elastic beantock will take the
backend code and put it on the internet.
So we'll wait for a few minutes for this
to complete.
Once that's done, we're going to click
this URL again.
And now instead of the sample
application, it should say index not
found, which is normal. This is how I
designed my back end.
Now in the URL, we're going to click up
here and go to the end. We're going to
enter the URL path slash API slash
products and press enter.
So this will give us the products data
that we were using in our project on our
computer. So this is the same data that
we saw before except now our backend is
on the internet.
Now that our back end is on the
internet, let's put our front end on the
internet as well. For the front end, we
also need to prepare our code. So, we'll
go back to VS Code.
And I'll collapse this folder for now.
And if we look at the front-end code,
notice that in here we use JSX code.
However, remember that the browser does
not understand JSX. It only understands
normal JavaScript. So, we need to
convert this code into normal JavaScript
first. To do that, VIT has a command for
this. Inside the command line, we'll
create a new tab.
And this time we'll cd into
ecommerce
dash project.
And vit has a command called npm run
build.
This is a shortcut for vit build.
So we'll press enter.
And this basically converts all of our
JSX code into normal JavaScript and
saves the code in a folder called dist.
So inside here we have an index.html
file and this is the HTML for our React
website. And inside the assets folder we
have this JavaScript file. So this is
all of our React code but converted into
normal JavaScript. You'll also notice
that Vit combined all of our code into
one file and it also minified or
compressed the code. So, it shortened
the variable names and removed the extra
spaces. This is because when we open a
website, our browser needs to download
all the front-end code and run it. By
combining and compressing the code, it
makes our website load faster. And Vit
did the same thing with the CSS.
You can see that it combined all of our
CSS files together and compressed it. So
now our front end is optimized and it's
ready to be put on the internet.
So now when we open a website, we need
to download this React code from
somewhere. So where do we put this
front-end code? So we could put this in
another service like GitHub pages and
then when we visit the website our
browser will download this front-end
code from there.
However, notice in our current setup
that we already have this backend
computer that's running in elastic
beantock.
So we can just reuse this backend
computer. we can put our React code into
the backend computer and our browser
will download the React code from the
backend computer. So, this is a common
setup and it simplifies our setup
because now we only need to set up one
computer. So, to do this step, all we
need to do is to take this disc folder
and then drag it into the e-commerce
back end like this.
And I added some code in the e-commerce
back end so that it works with this disc
folder. So now in the command line,
we'll go back to the tab that's running
in the back end and we're going to
create the zip file again. So we'll do
npm runzip.
So this will create another zip file but
with our front-end code inside.
And now we just need to upload this to
Elastic Beantock. We'll go back to the
browser
and open Elastic Beantock and we'll
click upload and deploy.
And we'll choose a file.
And this time we'll choose the second
file here
and click deploy.
And we'll wait a few minutes for this to
complete.
Once that's finished, we're going to
click this URL again.
And now we should have our React app on
the internet. So, let's try adding some
stuff to the cart to make sure it works.
I'll add a toaster and two plates.
And now, if I look at the cart, it
updated. If I open it, we have our new
products in the cart and we can update
them like usual.
And if we click create order,
it works. So everything is working the
same as on our computer, but this React
app is now on the internet. If we go
back to the homepage,
I'm going to give you a overview of how
this works. So visually, this is what's
happening. First we put our back end on
the internet. So the back end is running
on a separate computer and then we put
our front end code in the backend
computer and I set up some code in the
back end so that when we visit the
website using the URL path slash the
backend sends back the react code to our
computer. So now we have the react code
running on our computer and it
communicates with the backend running on
another computer. So, this is how a
realworld React app works. When we're
developing, the front end and the back
end run on the same computer because
it's easier for development.
But when we put the React app on the
internet, the front-end code runs on our
computer and the backend code runs on
another computer.
Next, we can add a shortcut to Vit to
make this process a little easier. We'll
go back to VS Code
and we'll go to the e-commerce project
folder which is here. So remember that
we created a disc folder and then
manually dragged it into e-commerce
backend. We can configure VIT to put the
disc folder in e-commerce backend
directly.
We're going to scroll down
to vit.config.js.
And in this configuration at the bottom
we're going to add a property called
build colon curly brackets. And in here
we'll use a property out capital D dur
colon and a string.
So this tells vit where to put the dist
folder.
So we want to put it inside the
e-commerce backend folder. So we'll give
it dot dot slash to go out of e-commerce
project and then into e-commerce
dashbackend
slashdist
and save.
So now if we go into the back end and we
rightclick and delete this disc folder
and then run npm run build. So in the
command line we'll open the tab that's
running in the e-commerce project and
then run npm run build and press enter.
It will create the disc folder directly
in here. So directly in the e-commerce
back end. So this just saves a step in
our process. We can also automate this
process further but I'll leave that as
an exercise.
So now we'll save this change into git.
We'll go to the git section
and we'll use the message save build
result in ecommerce dashbackend
and commit.
Before we continue, I want to discuss
how to deploy a react app without a
backend.
So notice that so far to put a React app
on the internet, we needed a backend.
But what if we don't know how to write
backend code yet? What if we just know
React? So if a React app does not have a
backend, we can actually just put the
code on the internet directly.
For example, in our code here, we're
going to go back to our chatbot project
from earlier. And notice that this
project does not use a backend. It only
has React code. So to deploy this
project, we're going to use npm run
build again. So in our command line,
we'll create a new tab
and we'll cd into the chatbot-
project folder.
And if we need to, we can npm install
and then npm run build.
And this will convert all the React code
into normal JavaScript and save it in a
disc folder again. So notice that inside
the disc folder, we actually just have
normal HTML, CSS, and JavaScript code.
So this is actually just an HTML website
and we can actually upload this code to
any service that puts an HTML website on
the internet. For example, here I use a
service called GitHub pages and I can
just upload this code to GitHub pages
and it will put it on the internet. No
backend knowledge required.
To learn more, you can actually follow
the same steps as my video, how to put a
HTML website on the internet. However,
make sure you do the exercises in this
lesson first since there's still some
small configuration changes that we need
to make for this to work. So, basically,
if we just have a front end, we can just
upload this code directly to the
internet using something like GitHub
pages. But if our project has a backend
as well, then we need to use a more
complicated service like AWS to put the
back end and the front end on the
internet.
In the rest of this lesson, we're going
to improve our AWS setup to make it more
real world and professional.
So, we'll go back to the browser
and we'll open AWS again. And I'm
actually going to close some of these
other tabs because we don't need them.
And inside Elastic Beantock in this
project, we're going to go to the
configuration section.
And we're going to scroll down and find
the configuration for instance traffic.
If you don't see this, you can check the
AWS troubleshooting guide in the
description.
So here we'll click edit.
and we're going to scroll until we find
the capacity section. And here we'll
look for something like environment type
and a drop down that says single
instance. So we're going to change this
to load balanced.
So what this does is it adds another
computer in front of our backend
computer. This is called a load
balancer. So what a load balancer does
is if we have a really busy website, one
computer might not be enough to handle
all the requests. So we can actually run
the back end on multiple computers and
this load balancer will distribute the
requests across these computers. This
allows our website to handle much more
users.
So here we can decide how many back-end
computers to run. Since we're just
testing, we'll set this to a minimum of
one and a maximum of one.
And then we'll scroll down
and click apply.
And now Elastic Beantock will set up a
load balancer computer in front of our
back end. And this will take a few
minutes to complete.
After it finishes, we're going to go
back to the configuration again
and we'll scroll down to the instance
traffic settings and just make sure that
min is one and max is one. If it's not
one, we can click edit
and then scroll back down and then
change it to one. And we'll scroll down
and click apply again.
So when that finishes, I'll just check
it again.
And now it's one and one.
So now our website setup looks like
this. We have three computers, the front
end, the back end, and the load
balancer. This is closer to a real world
setup. Again, you can watch my video on
backend overview to learn more about
these concepts.
Next, currently all the data for our
React app like the products, the cart,
and the orders are saved in a database
and the database is saved in a file.
However, when we put our React app on
the internet, we usually put the
database on a separate computer and this
lets us share the data between backend
computers.
So, inside AWS, we're going to go to the
configuration again
and we'll scroll down to the database
configuration and we'll click edit.
And inside the database section, we're
going to scroll down
and find database and we'll click enable
database.
Elastic Beantock will automatically
create a new computer that's running a
database and it will connect this
database to our back end.
So, we'll scroll down and look at these
options. And here we can select the
database that we want to use. So the
e-commerce back end works with the
database MySQL. So we're going to use
that.
And then here we're going to look at the
instance class setting. So this is the
size of the computer running the
database.
In the description, we'll click this
link, go to lesson 10, and then here
we'll follow the instructions to select
the correct instance class for the
database.
And finally, we'll set a password.
And now we'll scroll down to the bottom
and click apply.
So AWS will set up a separate computer
to run the database. And I already added
some code in my e-commerce back end to
connect to this database. So it should
just work. If you have issues, please
check the AWS troubleshooting guide.
After that finishes, we can open the
website again
and it still works. If we add something
to the cart, notice that the database
still works. And if we open the orders
page,
remember that earlier I created a new
order.
And now the orders are back to the
default values.
So this means that we're using the new
MySQL database that we set up. And now
our AWS setup looks like this. We have a
load balancer, a backend, and it
connects to a database on another
computer. And this is getting even
closer to a real world setup.
Next, if we go back to AWS,
notice that to open our website, we use
this default URL, which is really long.
So, now we're going to set up a domain
name to make our website easier to
access. A domain name is like myite.com
or youtube.com. It's a short name that
makes it easy to access our website.
So instead of putting this long URL in
the browser, we can just type myite.com
and it will open this website. So I'll
show you how to set up a domain name
with AWS.
First, we need to purchase a domain
name. Most domain names cost around $10
or $20 per year, so this section is
optional. If you already have a domain
name that you purchased before and you
want to use, feel free to skip to the
next section. Otherwise, I'm going to
show you how to purchase your own domain
name. There are many services we can use
to purchase domain names. I use a
service called namecheep for all my
websites like superimple.dev.
In the description, we'll click this
link, go to lesson 10, and click here to
go to namecheep. So, this is an
affiliate link. If you decide to
purchase a domain name using this link,
part of your purchase will help support
this channel. Thank you so much.
Once we're on NameCheep, we're going to
search for a domain name that we want.
If you see a search box here, you can
search for it. Otherwise, we can go to
domains and domain name search.
and we'll scroll down here
and search for a domain name. So, domain
names are unique. Once they are taken,
like youtube.com, we can't purchase it
anymore. If you don't know what domain
name you want, my recommendation is to
try to register your first and last
name. This might be useful for a
personal website. So, for me, it's Simon
Bao. and we need to give it an ending
like
do stands for commercial. It's the most
popular ending for domain names. Now,
you could pick another ending that you
want, but be careful because some domain
endings don't work with normal browsers.
If you're not sure which ending you
want, I recommend using com or.net just
to be safe because they are the most
popular.
So now I'm going to click search to see
if this domain has already been taken.
So it looks like this one has already
been taken. So I'll just add something
to it like Simon Balenge or Engineer.
And this one is available. So you might
need to modify your domain name to find
one that works for you.
So, we'll add this to the cart
and then open the cart.
If you want to autorenew this domain
name, you can click here and then we'll
click confirm order.
And if you don't have a name account,
you need to create an account first.
And after filling out all the
information, we'll purchase the domain.
And that's it. Now we have a domain name
and we own a little piece of the
internet.
Once we have a domain name, we're going
to set up the domain name in AWS.
So, we'll go back to AWS
and at the top we're going to search for
the service route 53
and we're going to write click this and
open in a new tab.
So, route 53 lets us manage our domain
names in AWS. We can click get started
and click create hosted zones
and then click get started.
If you don't see that, we can also click
this menu here,
click hosted zones
and then click create hosted zone.
A hosted zone lets us connect a domain
name to our app. So currently a hosted
zone costs about 1.6 6 cents per day. So
you can use it for free for a few hours.
So here we're going to enter the domain
name that we have. So for me it's simon
balenge.com
and scroll down and we'll leave it as a
public and then click create hosted
zone.
And now inside here, we're going to
scroll down and click create record.
So this sets where the domain name will
go. We're going to leave the subdomain
as blank and we'll create an A record
and we're going to check alias.
And here we can select which AWS service
we want to connect to.
So for us, we're using elastic beantock
and we're going to choose the region. If
we go back to the tab that's running
elastic beantock, we can see the region
up here. So for me, I'm using the region
Ohio.
So go back to route 53 and I'll search
for the region Ohio and select it. And
we should see our app here. So I'll
select that.
and then scroll down and click create
records.
And finally, we need to tell NameCheep
or the company that you use for your
domain name to redirect to AWS.
So inside NameCheep or your domain
company, we're going to go to the
settings
and we're going to find the domain. So
in namecheep it's in domain list
and here you may need to verify your
email. So we'll click this and check
your email for the verification. So this
might take a while. So we just have to
wait until the verification is complete.
And we may need to log out and log back
in to our NameCheep account for the
verification to update.
Once verification is complete, we should
be able to go back to the domain list,
find our domain, and open the settings
for the domain.
And in the settings, we're going to look
for a section that's called name
servers. If you're having trouble
finding this in namecheep or your domain
company, please check the AWS
troubleshooting guide in the
description.
And then in here, we're going to click
this dropown
and we're going to set custom DNS
because we're going to use AWS for this.
So now we need to enter some name
servers. To find these, we're going to
go back to AWS route 53.
And I need to zoom out a little bit to
see this. Inside the hosted zone, we
have some records here. and we're going
to look for the record NS or name
server.
So in the NS record, we should see these
four URLs here. So we just need to copy
these over to namecheep or your domain
company. So we'll select this and copy.
And then inside NameCheep
and here we'll paste.
And we'll go back and select the second
name server.
copy
and paste.
If we need to, we can add two more name
servers.
And here we'll select this and copy.
And here we'll paste.
And we'll select the last one. Copy.
And here paste. And then save.
So what this does is when we open our
domain name in the browser, NameCheep is
going to redirect to AWS and then AWS
will redirect to Elastic Beantock or to
our app.
So this setting will take a while to
update. Sometimes it finishes in just 10
minutes, but it could take up to 24 to
48 hours. So we just have to be patient.
So once we waited for a while, we can
try opening a new tab.
And in here we'll type http
colon double slash and our domain name.
So for me it's simon baenge.com
and press enter.
And this will redirect to our app. So
now we're able to access our React app
using a short domain name that's easy to
remember.
Next, I'm going to explain why we enter
HTTP in front and why we see this not
secure warning here. So this means that
our website is not using encryption.
This means that any data we send to this
website can be intercepted by a hacker.
To enable encryption on this website and
make it secure, we need to set up an SSL
certificate, which is a special file
that enables encryption.
To get an SSL certificate, we can use
AWS.
So, we'll go back to AWS Route 53 and
then at the top we'll search for another
service called certificate
manager
and click here
and we can request a certificate. If you
don't see it, you can also go in here
and click request certificate.
We'll use the default value and click
next.
And here we're going to enter our domain
name. Make sure to enter your domain
name.
And we'll scroll down and make sure DNS
validation is selected.
And scroll down and click request.
And then we'll wait for this to finish
loading.
And now AWS needs to confirm that we own
the domain name. That's why it says
pending validation.
To do that, we can just click this
create records in Route 53 button. If
you don't see this, please check the AWS
troubleshooting guide.
And it should show up here. And we'll
click create records.
And we'll wait for this to finish. We
may need to refresh a few times until it
says it was successful.
And now that we have an SSL certificate,
we can use this in elastic beantock. So
we'll go back to elastic beantock
and then in the configurations here,
we're going to scroll down to the
instance traffic settings and click
edit.
And we're going to scroll down
until we find this listeners section.
And here we'll click add listener.
For the port we're going to use 443.
And for the protocol we're going to use
HTTPS.
HTTPS means we're going to have a secure
connection to our website. And this
usually uses port 443.
And here we're going to choose the SSL
certificate that we just created.
And we should be able to leave the SSL
policy blank and click save.
If that didn't work, please check the
AWS troubleshooting guide. So this
basically adds an SSL certificate to the
load balancer. And now any data sent to
our website will be encrypted.
So, we're going to scroll down and click
apply.
And again, this will take a few minutes
to complete. So, we just have to wait
for it.
Once that's complete, I'll close some of
these other tabs
and I'll create a new tab.
And in the URL, we're going to type
https
colon double slash. So this tells the
browser to use the secure connection to
our website
and then we'll type our domain name. For
me, it's simonbowenge.com
and press enter.
So now the not secure warning is gone
and we're using a secure connection to
our website that uses encryption.
Also now if we just type our domain name
in the URL without HTTPS in front and
press enter
it will default to using the secure
version. So that's how we set up an SSL
certificate and HTTPS in AWS.
And now we have a professional and
realworld setup for our React app.
In this section, I'll show you how to
delete everything we created in AWS.
However, I recommend to do the exercises
of this lesson first to get more
practice with AWS and then do this
deletion.
Also, I try to keep everything we
created in the free tier. The only
exception is the hosted zone in Route
53. You can use it for free for a few
hours. So you could keep running these
services and practice AWS if you want to
check your AWS bill. We can go to the
profile and click billing and cost
management.
And now after you finish the exercises,
I'll show you how to delete everything
just in case. So in elastic beantock, we
can click this actions dropown and click
terminate environment.
And in here we need to type the name of
the environment which is here
and click terminate.
Once that's finished, we can go up here
and go to route 53.
And in this menu, we can go to hosted
zones.
and we'll open the hosted zone.
And inside here, we're going to select
the A record and the CNAME record and
delete these records.
And then at the top, we can delete the
hosted zone.
And in here, we'll type delete and click
delete.
Once that's finished, at the top, we'll
go to certificate manager.
And in this menu, we're going to click
list certificates.
And we'll select the certificate and
click delete.
Type delete and click delete.
You can also delete your entire account
if you want by clicking your profile and
clicking account
and then close account. Although you
lose access to the free tier if you do
this. I usually keep my account open for
a while to practice with the free tier.
So now we put our React app on the
internet and we created a professional
real world setup and that's the end of
this lesson. In this lesson we learned
AWS or Amazon Web Services which is a
collection of services that help us put
stuff on the internet. We learned EC2
which lets us rent a computer from AWS
and is known as infrastructure as a
service or IAS. We learned Elastic
Beantock which manages EC2 and sets up
all the software that we need. This is
also known as a platform as a service or
path. We put our backend on the
internet. We learned how to build and
optimize the front end and put it on the
internet. We learned how to deploy React
without a back end. We added a load
balancer and database to create a more
realworld setup. And we learned how to
set up a domain name, SSL certificate,
and HTTPS for our website.
Here are some exercises to help you
practice what we learned in this lesson.
In this lesson, we're going to learn
some of the updates in the new version
of React, and we'll learn how to use
TypeScript with React.
On the React website, there's a page
that lists the updates in the new
version of React. You can find a link to
this page in the description.
So there's a lot of changes here and
many of these changes are related to
using React in a framework which is
basically a layer on top of React.
For now I'm just going to go over the
changes that are related to this course.
The first change is called support for
document metadata. So this means that we
can put elements that normally go inside
the head section like the title, link
and meta elements directly inside our
component like this. So this lets us
change the head section when we render
this component. For example, in our
project, we used a title element to
change the text in the tab when we
switch pages. The way this works is when
this component renders, React will put
this title inside the head section and
this will change the text in the tab.
Before React 19, we had to use an npm
package like React helmet to do this.
After React 19, we can just put these
elements directly in our components. So,
it's easier.
Another change is called ref as a prop.
Earlier in this course, we learned about
refs and we can use a ref to get access
to an HTML element directly.
We can also give a ref to a component.
For example, if we want to get an HTML
element inside this component.
Before React 19, ref was a special prop.
We can't access it inside this
component. We had to use a feature
called forward ref.
After React 19, ref is now a normal
prop. We can access it like any other
prop and we don't need to know about
forward ref anymore, so it's easier.
The next change is the introduction of
the React compiler. The React compiler
optimizes our React code. For example,
let's say we had a component like this.
We have a counter and two other
components inside. When we click the
counter, this element will update, but
it will also recreate these other two
components. Even though clicking the
counter does not affect the other two
components.
That's because by default, when a
component updates, it will also update
or recreate all the components inside.
And this may cause performance issues.
To avoid this issue before React
compiler, we had to use three features.
Use memo, use callback, and memo. And
this prevents a component from being
recreated unless one of the props
changed.
So don't worry if you don't understand
this code because after the React
compiler, the compiler will just add
these optimizations automatically.
And now we can just write our code as
normal and we don't need to worry about
use memo, use callback or memo anymore
in most cases.
So again, the React compiler optimizes
our React code. All we have to do is to
set up the React compiler and we will
get these optimizations. We don't have
to change any of our code.
Now, let's learn how to set up the React
compiler in our project. In the
description, we'll click this link, go
to lesson 11, and here we have the
instructions for setting up the React
compiler. I put the setup instructions
here because this process might change
in the future, and it's not easy to
update the video. So, follow the
instructions that you see on your page.
For me, the first step is to install the
React compiler npm package. So, I'm
going to select this command and copy
it. And then in my project,
I'm going to go to the command line and
create a new tab. And I'll close these
other tabs so that I can start fresh.
And first, I need to make sure I'm
running inside e-commerce-pro.
So, cd ecommerce-
project
and then I'll paste the command
and press enter to install the react
compiler npm package.
And then I'll go back and the next
instruction is to copy this react
config. So, I'll select this config and
copy it.
And then I need to update vit.config.js.
js and put that react config in here. So
I'll go to the project
and open vit. doconfig.js.
And at the top I see this react config.
So I'm just going to replace it and
paste
and save.
And that's the setup. Again, the
instructions might be different when you
watch this video. So follow the
instructions on your page.
Next, let's check if the React compiler
is working. So, we'll go back to the
instructions
and down here we have some instructions
for checking if React compiler is
working. Again, follow the instructions
on your page because they might have
changed. So, first I'll start the back
end and the front end using mpm rundev.
I'll go back to VS Code
and in the command line I'll create a
new tab
and I'm going to go into the backend
folder using cd ecommerce-backend
and run mpm rundev.
And I'll go to the front end tab
and I'll also run mpm rundev.
So now both of them are running. I'll go
back to the instructions
and the next step is to install the
React DevTools Chrome extension. So
we'll click here.
So this is an extension made
specifically for React. It has a bunch
of features that help us with React
development.
So here we're going to add this
extension to our browser.
And once that's finished, I'll go back
to the instructions.
And the next step is in your project,
open the console and open the components
tab. So, in VS Code, we're going to open
this project in the browser
and I'm going to rightclick
and inspect.
And in the console, we're going to click
here. And we should have a new
components tab.
So, we'll click this.
If it gets stuck, you can refresh.
And this shows us all the React
components that are on our page. If we
scroll down and if we look at our
components, they should have a badge
beside them called memo. This means that
the React compiler is working and it's
optimizing our React components.
Now, let's go back and look at some more
changes in the new version of React.
The next change is removed prop types
and default props. So prop types were an
older feature of React. It basically
lets us check the type of a prop.
For example, here we can check if the
prop text is a string. If we run this
app and text is not a string, it would
show a warning in the console.
So now we use a different tool called
TypeScript which is better at this type
of type checking. So React removed the
prop types feature in favor of
TypeScript.
React also removed default props. If a
prop is undefined, this feature lets us
set a default value. So now we can do
this with normal JavaScript. So we don't
need this React feature anymore.
Now that we learned that propt types was
replaced by TypeScript, let's learn how
to set up TypeScript with React, we'll
go back to VS Code.
And to set up TypeScript with React, we
can use the create vit command. So in
the command line, we'll create a new tab
and make sure this is running in the
React course folder. And we're going to
run the command npx
create-ash vit. And we'll type at to
give it a specific version. And we'll
click this link in the description. Go
to lesson 11.
And we'll use this version of vit. So
copy the version that you see on your
page.
And here we'll paste
and press enter.
If it asks to install the package, press
Y and press enter.
And as a review, create VIT creates a
new project. So let's name this project
ecommerce-
project-ts
or TypeScript and press enter.
For the framework,
we're going to press down and choose
React.
And for the variant, we're going to
choose TypeScript.
So this will create a new React project
that uses TypeScript.
If we look at the code inside source,
notice that it uses tsx files instead of
JSX.
TSX means this code uses TypeScript
while JSX means it uses JavaScript.
So now to run this project, we're going
to follow the instructions that we see.
So for me, I'll cd into e-commerce
dash project-ts
and run npm install
to install all the packages that we
need.
And then I'm going to open the tab
that's running the front end. And I'll
press Ctrl C to stop the front end so we
don't have any issues. And then in the
TypeScript tab, we're going to run mpm
rundev to start this project.
And now we'll open this in the browser.
So I already have it open. So I'm going
to go in here and open this tab and
refresh.
Now we have a new React project. But
this project uses TypeScript instead of
JavaScript.
And now I'll give you an intro to
TypeScript.
Let's go back to our code.
And inside the TypeScript project, we're
going to open app.tsx.
So first of all, what is Typescript?
Typescript is just JavaScript with extra
features.
So notice that this TypeScript code is
the same as JavaScript code. The syntax
is the same and the features are the
same. For example, in here
in Typescript, we can create a variable
the same way as JavaScript using const
message equals the string hello.
And then we can console.log log message.
So as you can see, TypeScript is just
JavaScript.
However, TypeScript gives us some extra
features on top of JavaScript. The main
feature is we can add types to our
variables.
So what are types? Remember that
JavaScript has different types of values
like numbers, strings, and objects.
In Typescript, we can set what type of
value is inside a variable.
For example, in this variable, we have a
string. So, after the variable name, we
can type colon space and string.
So, this tells TypeScript that this
variable contains a string.
So now below this if I type message and
then dot TypeScript knows that this is a
string. So now it's able to suggest all
the features of a string like two
lowercase
and brackets.
So using TypeScript our computer can
give us better autocomplete suggestions.
Next, if I type message
to fixed and brackets,
two fixed only works with numbers.
Because TypeScript knows that this is a
string, it's going to give us an error
saying that too does not work on
strings.
So, this feature is called type
checking. TypeScript checks if this code
works with this type of value and this
helps us avoid errors. In JavaScript,
there is no type checking. So if I want
to put this code on my website,
JavaScript will just let me do it and it
will crash my website. But in
Typescript, if I want to put this code
on my website, I would save this code
and then in my command line, press
control C to stop the server and run npm
run build.
Notice that TypeScript actually blocks
us from building this code and putting
it on our website because there's an
error with the types.
So, as you can see, TypeScript gives us
type checking, which helps us avoid a
lot of these coding errors and helps us
keep our code safer.
Another feature of TypeScript is type
inference. Type inference means
TypeScript can figure out the type
automatically.
For example, in this code, this variable
obviously contains a string. So we
actually don't need to set the type
manually here. If we delete this type,
TypeScript will infer or figure out that
this is a string. So I can remove it and
save
and the error check still works because
TypeScript knows that this is a string.
Another example of type inference is up
here in use state. So this count
variable contains the number zero.
TypeScript will infer or figure out that
count is a number.
So if we do count to two lowercase and
brackets, it's going to give us an error
because two lowercase only works with
strings and TypeScript figured out that
this is a number. So, as you can see,
TypeScript is just JavaScript, but it
adds extra features like type checking
and type inference to our code, and this
helps us find and avoid errors. So, now
let's save this code. And we'll save
these changes into git. In the git
section
at the top, we're going to use the
message create new React TypeScript
project
and press commit.
So, we just learned how to create a new
React project that uses TypeScript.
Now, let's learn how to convert an
existing project, like our e-commerce
project, to Typescript. To do that,
we're just going to move all of our
changes over to the new TypeScript
project.
Before we begin, if you have any issues
during this process, please check the
troubleshooting guide in the description
since things might change depending on
the version of VIT.
To make this easier in the e-commerce
project, we're going to delete the node
modules folder for now.
And then we'll make a copy of this
folder. So we'll rightclick,
copy,
and we'll collapse these folders and
click the outside and rightclick and
paste.
So, this just helps us keep track of
progress when we're moving the changes
over. So, we're going to start from top
to bottom. First, we'll look at the
public folder. So, in here, the change
we made is we added this images folder.
So, we're going to take the public
folder and we're going to drag it to the
TypeScript project
and click move
and click replace.
Next, let's go into the source folder
and we're going to move our changes over
one by one. So, first in the assets
folder,
we didn't make any changes to this
folder, so we're not going to move it
over and we can just delete this folder.
As a reminder, we're not trying to move
all of our code over. We want to start
from a default TypeScript project and
then only move our changes over to the
new project.
So let's continue and look at the
components folder. So this folder is
completely new. So we're going to move
this entire folder over to the
TypeScript project inside the source
folder
and click move.
And if it asks to update the imports,
we're going to click no because we're
going to move everything over.
Next, we're going to go back up and the
pages folder is new. So, we're going to
drag this folder into the TypeScript
project inside source
and click move
and update the imports. Click no.
Next, we'll scroll up and the utils
folder is new. So, we're going to select
this folder and drag it into the
TypeScript folder inside source. So,
move and click no.
And next, we'll keep going one by one.
For app.css,
we made it empty. So, we're going to
move this over. So, drag it into source.
Click move and click replace
and scroll back up for app.jsx.
We made a bunch of changes in here. So,
we're going to move this over. So, drag
it into source
and click move.
However, notice in the TypeScript
project, the file is called app.tsx.
So, we're going to replace this code
with our file. So, first we're going to
select this and delete app.tsx.
And then we'll rightclick app.jsx
and rename
and rename it to tsx.
Now, we'll scroll back up and continue
moving our changes.
So, index.css,
we completely changed this file. So,
we're going to move it into the
TypeScript project into source.
Click move and click replace
and scroll back up. And finally, in
main.jsx,
we just added the router. So, let's move
this file as well. We'll select it and
drag it into source
and move.
And again in Typescript the file is
called main.tsx.
We'll select it and delete.
And we're going to rename our file.
Right click, rename
main.tsx,
and press enter.
Update the imports. Select no.
We'll scroll back up and we moved all of
the code from the source folder so we
can delete it.
Next, we don't need to move the starting
code folder because this was just for
practice when we were setting up this
project. So, we can just delete this
folder.
Now, let's move all the files over to
the TypeScript project. So in git
ignore, we didn't make any changes to
this file, so we don't need to move it
over and we can delete it.
In eslint.config.js,
we added one change to this file at the
bottom, which is we added this rule to
disable prop types. So we'll select this
code and copy.
And in the TypeScript project, we're
going to open eslint.config.
And at the bottom in this rules object,
we're going to paste and move that
change over and save.
So again, we don't want to move all of
our code over. We just want to move the
changes over because a lot of this code
is specific to TypeScript.
So, we'll scroll back up here and we can
delete this file because we moved it
over.
Next, let's keep going in here. For
index.html,
we changed a few parts of this code. So,
we're going to move these changes over
to help us compare this code with the
TypeScript version. I'm going to scroll
down
and take this index.html HTML and then
move it at the bottom here so that I can
compare these side by side.
So first the first three lines here we
did not make any changes so we can skip
them.
And then here the next three lines we
also did not make any changes so we can
skip them. And here we added a base
element. So we're going to select this
and copy. And in the TypeScript version,
we're going to paste that change.
And here we also deleted the title. So
in the TypeScript version, we're also
going to delete the title.
And here we added a font called Roboto.
So we're going to move this change by
selecting it and copy.
And in here we'll paste the font. And if
we need to fix the formatting, we can
select this and press shift tab to
remove some indents
and I'll scroll down.
And for the rest of the code, we did not
make any changes. So now we moved all
the changes over. I'm going to save this
file and close this for now.
And then in the copy, we can delete
index.html.
And next, we don't need to move packaged
lock.json over because this will be
autogenerated when we npm install. So,
we can just delete this file
and I'll scroll back up
and we'll move over package.json.
In this file, we didn't change anything
at the top, but we did add some
dependencies and dev dependencies. So,
we're going to move these over. We'll
select the dependencies and copy.
And then in the TypeScript project, open
package.json.
And in these dependencies,
we'll type comma and paste.
And then we'll remove any duplicates.
So, we'll remove React and React DOM and
save.
And we'll scroll back up
and open package.json.
And we'll do the same thing with the dev
dependencies. So, we'll select all these
dependencies
and copy.
And in the TypeScript project
package.json JSON in the dev
dependencies at the bottom we'll type
comma and paste
and we'll remove all these duplicates.
So I'll remove eslint
and I'll remove these duplicates
and these duplicates
and these duplicates
and remove this
until there are no more duplicates
remaining.
And now we'll save.
And then we're going to run npm install
to make sure we successfully install all
these packages. In the command line,
we'll go to the tab for the TypeScript
project and we'll run npm install.
And now we can scroll up and delete
package.json.
And we'll keep going for readme.md. We
didn't change this file. So we can
delete it.
And this file setup test.js is new. So
we'll move this over to the TypeScript
project.
And we'll scroll up and we're going to
move over vit.config.js.
So in here we added a bunch of
configurations.
So in the TypeScript project
we're going to drag vit.config.ts ts at
the bottom
and we're going to move our changes
over. So, inside the config,
we added some stuff for the React
config. So, we're going to select this
React config and copy
and then select this code, remove it,
and paste.
And we'll keep going. So, all of these
configs are new. So, we can just select
this code
and then copy.
And inside the TypeScript version, we're
going to paste
and save.
So, now we moved all of our changes over
to the new project. And we can delete
this file.
And I'll close this for now.
And finally, vtest.config.js.
JS is new. So, we can drag it into the
project.
And now we moved all of our changes over
into the TypeScript project. And I can
delete this copy.
Next, we're going to go into the
TypeScript project and we're going to
fix the errors. First, we'll open
main.tsx.
And in here, instead of importing from
app.jsx,
the file is now app.tsx.
So we're going to update that.
Also, we have an error here. So this
code tries to get an element from the
page using the ID root. However, this
element might not exist. So TypeScript
gives us an error telling us this value
might be null. However, if we check our
index.html
and scroll down, we have an element here
with the ID of root. So, we know that
this element definitely exists.
In main.tsx,
to tell Typescript that this value
definitely exists. At the end, we're
going to add exclamation and save.
So this tells Typescript that this value
definitely exists and it will not be
null. And now the error is gone.
Next we'll open app.tsx.
And up here we get some errors when we
are trying to import these files. The
reason we get these errors is because
these files are still.jsx
files or JavaScript files. So, we could
rename all of our files totsx,
but then Typescript will start doing
type checking in these files and we may
get a bunch of errors.
Instead,
in our files, we can scroll down to
tsconfig.app.json.
And inside here,
we're going to add a setting double
quotes allow capital J S
colon true and comma
and save.
So this setting lets us mix TypeScript
and JavaScript files in our project. So
now in app.tsx, tsx.
Our TypeScript code can also import from
JavaScript files and it won't cause an
error. So the allowJS setting lets us
gradually convert a JavaScript project
to TypeScript, one file at a time.
Now that we fixed the errors, let's run
this project again to see if our
e-commerce project works with
TypeScript. in the command line. Make
sure you're in e-commerce project ts and
we're going to npm rundev
and press enter.
And now if we open this URL in the
browser
and refresh
and now you can see that our e-commerce
project is working with TypeScript. If
we try some of the features like add to
cart, you'll see that everything still
works. If this does not work for you,
you can check the troubleshooting guide
in the description.
Now, let's go back to our code
and let's rename our folders so that we
use TypeScript by default. We're going
to scroll up and we're going to rename
e-commerce project. Right click, rename
to e-commerce project dashjs
for JavaScript.
And then we're going to rename
e-commerce project-ts
to e-commerce project.
So now by default our project will be
using TypeScript.
And just to make sure, we're going to go
to the command line and stop the V
server. And we're going to delete all
our tabs. So here we'll also control C
to stop the back end and delete all the
tabs. And then we'll reopen the command
line using the terminal menu and new
terminal.
And we're going to restart the back end
using cd ecommerce-backend
mpm rundev
and create a new tab
and we'll run the front end cd
ecommerce- project
and npm rundev.
And in the browser, we'll refresh
and our TypeScript project still works.
We'll go to VS Code. And finally, we're
going to organize these folders a little
bit. So, right now, we're no longer
using the e-commerce project JavaScript
version or the React basics folder. So,
let's click outside and we'll click here
to create a new folder. and let's call
it old dash projects.
And then we'll drag the JavaScript
version into here.
And we'll move React Basics into here.
So now our folders are a little bit more
organized.
So now let's save this into Git. We'll
open the git section and at the top
we'll use the message convert e-commerce
project to type script and commit.
Next we're going to learn an intro to
TypeScript with React. First, we'll go
into our files
and in the project, we're going to go to
source the utils folder and we're going
to look at money.js.
Currently, this is a JavaScript file.
That means there is no type checking in
this code. So, we're going to convert
this to TypeScript by right-clicking
and rename.
And we'll rename it to money.t. ts or
typescript.
So this converts the file into
typescript and now it will enable type
checking and now we will get an error
here.
So this error says amount sent
implicitly has an any type. So what this
means is that earlier we learned the
feature type inference which means
typescript can figure out the type
automatically.
However, in this situation, TypeScript
does not have enough information to
figure out the type of amount sets. So,
we have to set the type manually.
To set the type of a parameter after
this parameter, we're going to type
colon space and then the type of this
value. So, in this case, amount sent
should be a number. So, we're going to
type number and save.
And now that TypeScript knows what type
of value this is, the error will go
away. And now we successfully converted
this file to TypeScript.
Let's do another example. We're going to
go to the components folder and we're
going to convert header.jsx into
TypeScript. So we're going to rename
this file
to header.tsx.
So tsx is just a TypeScript file, but
the X means we can write HTML inside
this file. So it's just like JSX except
it uses TypeScript.
So now this converts the file to
TypeScript and it enables type checking
and we get some errors here.
If we look at this error,
we get a similar error. Cart implicitly
has an any type. So again, this means
that TypeScript does not have enough
information to figure out the type of
cart automatically. So we have to set
the type manually.
We might try to add the type after cart
like this. However, this is not how we
add a type to this code because remember
this code is actually a shortcut for
this code. This is called the
dstructuring shortcut.
So this whole thing is the parameter.
So we need to add the type here
after the parameter.
So this code is a shortcut for props
which is an object. To tell Typescript
that this is an object here we're going
to type curly brackets
and then inside here we can also tell
TypeScript what properties are in this
object. So in this object we have a cart
property. So in the type we're also
going to add a cart property. And
remember that the cart is an array like
this.
So we're also going to tell Typescript
that this cart is an array using colon
and square bracket semicolon.
So again, this code tells Typescript
that this value is an object with a
property called cart and the cart is an
array.
Next, we can also tell Typescript what
is inside this array. In front of the
array, we can type curly brackets to
tell Typescript that this is an array of
objects.
And inside this object, we can also tell
TypeScript what properties each object
has. So inside our cart array, each
object has a product ID and this product
ID is a string. So we can tell that to
TypeScript using colon string semicolon
and each object also has a quantity and
this is a number. So we can tell that to
Typescript using colon number semicolon
and each object has a delivery option ID
which is a string. So colon string
semicolon.
So using this code we can tell
Typescript exactly what type of value
this is. It's an object with a property
called cart. And the cart is an array.
And each value in the array has these
three properties.
So now TypeScript can actually look at
the rest of our code and check if each
value in the array has a quantity
and if we accidentally misspell quantity
here like this. TypeScript can use this
type here to check if we made a mistake.
So this helps us avoid a lot of mistakes
when we're coding. So, let's add that
back and save.
Next, we're going to organize this code
a little bit. So, putting a complex type
directly in the code like this is a
little hard to read. So, we can actually
take this type and then save it
separately.
above this component we can use type
space and then give this a name.
So here this value is the props for the
header component. So we'll name this
header props and we'll type equal and
we're going to move this type up here.
So we'll select this type and cut.
And then in here we're going to paste.
So this is called a type alias and it
works just like a variable but for
types. So we can save a type in here and
then we can use this type later in our
code. For example, down here, we can
just use this type header props
and it will substitute this type into
our code just like a variable.
And now our code is much cleaner. So
that's an intro to how to use TypeScript
with React. We basically add types to
React features like props.
So now let's save
and we'll save these changes into git.
In the git section
at the top we'll use the message convert
money utils and header to type script
and commit.
Finally, we're going to learn how to use
AI or artificial intelligence with
React. After we learn React, we can use
AI to help us write React code faster.
The easiest way to get started with AI
is to use GitHub Copilot, which is built
into VS Code. Before we begin, AI tools
are changing very quickly. If something
in this section is not working, you can
check the troubleshooting guide in the
description.
To set up GitHub Copilot, we're going to
install the GitHub Copilot extension.
So, in the extension section, we need to
make sure we have the GitHub Copilot
extension installed. If it's not
installed, we can search up here for
GitHub Copilot
and install this extension.
Once we have that installed,
we're going to click this C-pilot icon
up here and we'll need to log in to our
GitHub account. So, we'll click sign in
and then we need to log in to GitHub. If
you don't have a GitHub account, you can
create one by clicking here or going to
github.com.
So, I'm going to log into my GitHub
account
and then I'll click continue
and I'll click here to go back to VS
Code.
Once we finish the setup, we can start
using some features of AI. The first
feature is autocomplete.
So, let's say that we're in the header
and we'll close this window for now.
And let's scroll down to the HTML
and we're going to go to the right
section.
Let's say that inside the header, we
want to add a link to a login page. So
here we can just start typing in this
code
and the AI will give us some
autocomplete suggestions. To accept
these suggestions, we can press tab.
So this creates a new link and some
text. And I'll press enter.
And it gives another suggestion. So I
press tab.
And this creates the closing tag for the
link.
So you notice that the autocomplete is
very smart because the AI can read and
understand the rest of our code and it
can suggest code that follows the same
patterns as the rest of our code. For
example, here it creates a link element
and it gave it a class name that is
similar to the other class names.
However, when using AI, we may need to
go in and modify things to make sure we
get exactly what we want. So, here the
AI created a link to the homepage, but
what we actually want is a link to a
login page. So, I can click here and
modify the URL path to slash login.
And I can also change the text to login.
And I'll change this to login. And I
don't really have an icon for the login
page. So we can delete it.
And I'll change this to login.
So using AI, I'm able to write this code
a lot faster.
Another feature of AI is we can give the
AI instructions.
For example, let's remove this code for
now.
And we can click this copilot icon.
and it will open this chat window. And
inside here we can just tell the AI what
we want to do. For example, in here we
can say in the header
add a link to the login page and make
sure in this dropdown you have agent or
edit selected
and we'll press enter.
and the AI will make edits to our code.
So here you can see that it added a
login link like before. So we can press
keep to keep these changes or undo if we
don't like these changes. So this looks
good to me. So I'm going to press keep.
And again I'll go in here and modify it
a bit. So here it added the login link
after the orders link but I want to put
this before the orders. So I can just
select this code and cut
and at the top
paste that code.
So, as you can see, by using AI, we can
write React code faster. But you'll
notice that we still need to understand
the code to check if it's what we want
and to modify the code if we need to.
So, it's important to learn how to code
first and then we can use AI to help us
code faster. So now I'll go into the git
section and I'm actually going to undo
these changes because this was just an
example.
And that's the end of this lesson. In
this lesson, we learned some of the
updates in the new version of React. We
learned how to set up the React compiler
to automatically optimize our React
code. We set up a new Typescript React
project using create vit. We did an
intro to TypeScript and learned basic
features like type checking and type
inference. We converted our e-commerce
project to TypeScript.
We learned how to use TypeScript with
React. And we learned how to use AI with
React to help us write code faster. Here
are some exercises to help you practice
what we learned in this lesson.
Good job on finishing this React
tutorial. If you want to continue
learning with me, you can check out the
premium version of this course where I
will be adding extra lessons and
projects in the future. Currently, the
premium version has 11 lessons, but I'll
be adding more lessons in the future.
You can also check out the membership
for extra content on AI and backend.
As the next step after learning React, I
recommend moving to the back end and
learning the command line and NodeJS.
I'll be putting my work in progress on
these technologies inside the membership
first, so be on the lookout for that.
Thanks so much for watching and taking
this course with me and I'll see you in
the next one.
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.