Lesson 09
Intro to ReactJS - Bootcamp Day 9 (2024-09-10)
Source Code: https://github.com/nbktechworld/full-stack-web-dev-3/tree/4687757052a413328b600cfe4ec69f5606632020
A brief introduction to creating websites and web applications with the React library.
The lecture teaches you how to generate a new ReactJS project using create-react-app.
Then you get an overview of how user interfaces are built in the frontend with React.
The lecture goes over converting the Messages page to a React component.
You learn the React syntax and how you can write templates in JSX, a notation that looks like HTML.
The lecture also goes over event handler functions, keeping track of state, and generating components dynamically with the map function.
Video Transcript
So, today I will talk about the React library to build user interfaces on the front end.
So we have learned so far HTML, CSS, and JavaScript, the three main pillars of front-end development.
But now we're going to go beyond that.
For the JavaScript part, if you saw from the previous lesson, there's a lot of
problematic and tedious stuff that we have to do to manipulate the document.
And what if we could deal away with that and actually build a system where that is all taking
care for us and all we have to do is focus on the basics, pretty much focus on declaring tags
in a way that we do with HTML. And then we get the additional bonus of being able to use the
JavaScript programming language at the same time. And that's the point of having a framework or
library like React. Now, React is not the only one that allows you to do this. There are other ones
like Angular, ViewJS, and many others. But React is one of the most popular ones and is the one
we're going to do today. Now, before we proceed, we need to have a Node.js installed. So here's the
website. If you go to Node.js.org, make sure to install it. The bundle also comes with NPM,
the Node package manager, which allows you to install third-party packages,
which is basically code that somebody else wrote, and we want to incorporate it into our project.
Okay, with that said, so we're going to talk about React. So let's first install,
generate a project with React, and then we talk more about it. Now, there's a lot of
boilerplate. Just like HTML, we have to type all those tags, boilerplate, React has its own
boilerplate to set up all the tooling and stuff like that. In order for us to avoid doing that,
there's already something that somebody else built called create React app. So we're going to use
that to generate a project. So first, I have to open a terminal window. You can either do that
from your text editor like Visual Studio Code, or you can just open a standard long version. If
you're on Mac, it's the terminal app or iterm2, if you have installed that. If you're on Linux,
the same terminal. On Windows, it's either command prompt, power shell, git dash, or even Windows
terminal. Anyway, like I said before, if you want to find out if you have Node installed without
an issue, you can open a new terminal window and type these commands, Node dash V, and NPM dash V.
And you should see the version number. Anyway, I am, I have CD or change directory to my
post stack web.3 folder. And I'm going to use the command NPX, which only works if you have NPM,
but it's NPX, okay, space create dash React dash app, that's the name of the package.
We're going to leverage the tool space, and then I'm going to give a name to this project,
and that will be the directory name. Let's call it web client separated by dash or lowercase.
Now I might take some time to install all the dependencies for the project and generate it.
Okay. So basically what's happening is Node package manager NPM is downloading all of the
source code that somebody else wrote and putting it in our local machine in a directory called
Node modules. And that way we are leveraging the work that somebody else already did. So we
don't have to reinvent the wheel every time just to build a React application. So it's made
the process really easy to get started with React. Whereas before if you were to do it manually,
maybe many people get frustrated and they don't understand what's going on.
So let's wait a little bit. You can see it's installing the React, React dash DOM,
React scripts, and CRA dash template packages.
By the way, these modules, they're downloaded from a registry, and the main one is called
npmjs.com, that's the website. If you want to go there and see what it looks like, it comes from there.
Okay. You should be able to see all these hints of how to run the project. But nevertheless,
we want to follow what it says. First, you want to CD or change directory to web dash client like
this. Make sure to do that first, otherwise not going to work. Make sure you are in the directory
web client. And then what you're going to do is, first, you can open your source code with your
text editor. I'm using Visual Studio code. So what I do is I type code space dot to get it.
Okay. I already have it open. So I'm not going to do it. And then after that, you can start the
development server. So we always have to start this command to power up the development server.
So npm space start. Now this is going to run the server that will make the app available for us to
access through the browser. Usually it opens the browser automatically for you. So it might take
some time while it's doing that. What I'm going to do is I'm going to go to Visual Studio code,
explore the source code. So under web client directory. This is what the structure looks like.
So we have this file called package.json, which every npm or no jazz project has.
And this file has some math to that about the project. And it's particularly important this
property called dependencies. This each line lists a dependency that you have on somebody else's code.
So their code is encapsulated in what we call in a package or sometimes called module.
So we are dependent on react library here. And the right hand side is the value. And that's the
version that's we're using. We're using the reactive version 18.3.1. Okay, so this is basically a
file that kind of holds a JavaScript object like we learned in the last lecture. Hence the name
the abbreviation J S O N which stands for JavaScript object notation. It's a way of like
keeping data in this specific format. Anyway, SRC is what we're interested in stands for the
source code is where all the source code is. In particular, you want to look at app.js and
index.js index.js will be the entry point of how the react app is injected. And then app.js is the
actual template for what you see on the screen. So let's look at the terminal again.
The terminal says that everything's been compiled successfully. So you can go through your browser
and access this link here. You can even control and click it that works as well. It's basically
you got to type local host colon 3000. Now this is like the domain. Usually in the actual
production application would be like www.your website.com something like that. And in this case,
3000 is the port number. Okay, let's go and check it out in the browser. So I'm going to open Chrome
here. Share with you. I'm going to open a new tab. I'm going to do local host colon 8. Sorry,
is it 3000, right? There you go. And this is the application that's loaded.
It's the boilerplate that they add. If you want to inspect that by F12 elements, you can see
what it looks like. So the whole react application is contained in this div element here.
Here's the IMG, here's the paragraph a and so on.
So let's talk more about react and let's new what's so innovative.
So previously, we built HTML files pages, right with files.html like index, let me put the live
preview here. But those who don't know I'm using Visual Studio Code extension live preview, and I
install the one for the first result from Microsoft here. And then I can do the live preview when I go
to the Explorer, click index, and I do control shift B, or I click view command palette, live
preview show preview internal browser, I can see it on the side. So previously, we built simple
pages like this, starting from the entry point index, which is the root. So I could go to like
news.html here by clicking this link. And then I can go to sign in, and then I can go to the
messages that I didn't have a link to, but it's basically messages.html, and all that stuff.
If you notice, there's a one HTML file for each page. And it's kind of tedious, because it's
always the same boilerplate for the doc type HTML had some links, and it's kind of tedious because
HTML had some link tags are almost the same. So it's kind of tedious. Imagine a website has
thousands, not hundreds of thousands of pages. This would be really hard. But if I want to change
the header that appears in every single page, I would have to change like 10,000 files to change
the same code, right? So that's not what we usually do in practice. We usually have a single page
layout that defines the layout of the website. And all that changes is the main content.
As you go about navigating the website, all that changes the main content. So that's what we usually
do. Now, let's talk about the concept that React introduced. So if you notice from the example
we did for messages, this page here, we use JavaScript to actually inject a new message
every time I type and click the button right message. And we did so writing code here in this
function add message to list. And it's very tedious, it's programmatic programming of the user
interface, which is kind of go against HTML, where we declare tags and declare what we want to see.
So this approach has, you can imagine, at scale is going to be really messy. This is a really simple
website. And it's already kind of a lot of stuff going on here. So that can get messy really fast.
So how do we approach that is like the goal of React to make this simpler. So we're going to
first have to understand the concept of single page application. So traditionally, when you have a
website and you click a link, the browser will download the HTML file, and then parse it and
show it to you. So every single page would cause a reload, right? The page will be reloaded all
over again. And then somebody a long, some time ago, they said, okay, why why you keep doing this?
How about we make websites act like, for example, desktop applications, that's what was more popular
at the time. And they're so smooth, there's no this waiting, you click the link and then everything
goes blank, you got a new page and everything goes all over again. So somebody had an idea why not,
we use JavaScript to build the whole page on the users browser side instead of us always having
to rebuild it on the server side, as we serve the page. So hence came the concept of single page
application, SBA. So basically, what you have is the first time you request a website, it sends you
the whole HTML page. And then the browser, the client side, which is the person's computer will
be in charge of building the website from scratch using JavaScript. So usually you get a blank page
from the server. And then the client will be make sure, okay, let's build all the message list.
Let's build all these comments, all these profile pictures and so on and so on. So that that's the
goal there. And then when you want to show something else like a different page quotes,
it's actually just manipulating the document and rewriting it and showing a different content
by using JavaScript to remove elements, add new elements and so on. But in this process,
you're never really reloading the page, never ever, you're just asking the server for information,
hey, could you give me all these posts? Can you give me this link to the image I'm about to show
something like that? You're never asking for a whole HTML page. So that's the concept of single
page application. And it's important to understand that because I'm going to show you the difference
in Chrome just now. So I'm in Chrome, I want to go back to the pages we built with plain HTML,
CSS and JavaScript, this one, I want to open the source code. So right click, click,
view page source. And you can see, I can see my paragraph, hello, I can see my links and everything
in the page here. Right. So the server sent me this HTML file, and it already includes all of the
content. Great. Now let's look at the React application that we just powered up. This is the
one I'm going to close this and right click the view page source. And if you notice here at the
body, that's what people see, you only have this div with nothing inside, that's a div of the ID
root. And that's what the server sends the client, you receive a HTML page that's blank. There's
nothing. But when you see the actual page, there's something what is going on here. It's because
this whole thing was built after you received the HTML page using JavaScript. So if you were to open
the live document preview with the dev tools under the elements tab, you actually see inside the root
if you expand, that's the whole app with a div and header and everything else. So this part of
DevTools is the live view, which shows you the document as it is right now, which is different
from the view source, which is the document file as it was sent from the server. Okay. So that's
why it's different. But nevertheless, the point is the single page application builds itself in a
client. So that's what's going on there. Anyway, now do you understand that concept? We can move on
and do some react and understand how it is built. Let's go here. So how are we going to build this
with react? Well, what happened is we have this file index.js. And in this file, it's calling here,
get element by ID. Remember that that's defined an element in the document by the ID. So it's
finding that div of the root ID root. And it's injecting this app there. So react is doing all
the work to build all that stuff for us. So we don't have to write the JavaScript code to do that.
It's all delegated to the library or framework. Okay. So yeah, so there's a lot of stuff happening
behind the scenes. And you don't have to worry about it. The whole goal of using react is you
focus on building user interfaces, you don't have to worry about how it's going to be built or
constructed on client side. That's the whole point. React is always watching and seeing. And it's
all it's going to ask of you, hey, I want to know how you want this app to look like. What's the
user interface going to show? And then I'm going to take that and compare with what I see in the
browser. And if there's any discrepancy react will just build it for us automatically. So we don't
have to write all the JavaScript stuff. Alright, so then that there's this file app.js. And it's
basically a file that contains a function definition called app. And that function returns
something and that's something is something is a template that looks like HTML. So as you can see,
there's a div, there's a header inside the div, there's an image or paragraph, an anchor tag,
which is basically what you see in the Chrome, right? You recall here, let me share again,
this thing is defined there in that return value for the function.
Now, it might seem odd, this is a JavaScript file, why do we have HTML and JavaScript? Well,
actually, this is not HTML, it's called a JSX. Okay, and it's basically, it's kind of like a front,
they call it syntactic sugar. Behind the scenes, it's actually a function call in JavaScript to
react dot create element every time you create this tag here. But you don't have to know that
because the whole goal for them to kind of hide that behind the scenes is so you can write it
just like HTML. That's the whole point of react, write it as though it's HTML. All right, so you
can just start building stuff with this change the code here, let's say, I remove all the stuff I
just want to do. And I'll say a paragraph Hello world. And then I can add some random
sentence Lauren 10 tab. Oh, it is not working. Why? It's probably because not HTML. Hey, there.
Save that. And the great thing about using create react app is when you save this file,
you have like hot reload. So when you go and look at your browser, it's automatically reloaded for
you. You don't have to click reload yourself there to see hello or hey, there's there.
Okay. So all you have to do react is create a function. And this function is called a component.
Okay, that's what they call react. In HTML, we have elements. In react, we call them components.
It's like building your own HTML element. Okay. So let's try to build that messages thing with
react. Let me put this on the we put that editor layout split down. So I have this file messages
HTML that we build. And I want to write this in react, how would I go about that? Well,
let's think about this. So let's create here a function.
I'll call it messages. Notice I always capitalize the first letter and that's important because
it's a convention that we follow for react components, that the function will have the
first letter of its name always capitalized. And then it's a function definition parenthesis there.
And I'm not going to put any or parameters there yet. I don't need it right now. But usually there
is, they're called props. Anyway, in this function, I always return the template for what I want
the page or this piece of the user interface to look like. So pretty much you can just go to the
message HTML to the body, whatever is between the open and close body, except for the script,
you don't want the script, you copy that and place it here in the return value
build a function. And let me fix my indentation.
Now there's some stuff we've got to change for react. So bear with me.
So the first thing is I forget the
okay, the first thing here that mess this is messed up is react is complaining. And if you have
visual studio code, it has this kind of extension. It's telling me there's an error.
JSX expressions must have one parent element. So if I say this like that,
I just want to show you what it looks like when an error is out.
It's going to give me an error. So you can see that in the browser, and you can read that.
There's an error in the file source slash after JS. And it's telling you some stuff. And
adjacent JSX elements must be wrapped in an enclosing tag. Did you want a fragment if this is
the suggestion to how to fix it. And it's basically telling you the line seven, there's a problem.
Okay, I just wanted to show you this so you can see how to read the errors.
But basically a function in JavaScript can only return one thing. But in this case, you have like
one, two, three things. So there are multiple ways to get around that you can enclose everything in
a div like this. That's one way of fixing it. And then they created a new way called the fragment.
And the difference is the fragment doesn't introduce an extra intermediate div.
Let me show you what that means. So here's the app running on open up the dev tools with f12.
And I'm going to click here to inspect this. And you can see there's the div root,
and the div of hello world hey there. So this div is what we just wrote. So some people don't
like to have this do what's the point have this extra div here. I can just get rid of it. So to do
that, you can just use the fragment, you can say react dot fragment oops, here, like that. And then
you close the tag with the same name. Like that's just like HTML. Now, because you're using something
the JavaScript file doesn't know about it's complaining. What is this is not defined,
you have to go and import that. So usually at the top of the file you see all these imports.
That's the point of that. So you're going to import react like this. So you're going to define this
symbol from somewhere that somewhere is the react package from npm on the you have to have the
quotes. And how do I know this name that's from the package Jason here this name here. So if you
need to import any of these things you can just import whatever from the name here.
Anyway, going back now it's defined. And it works just the same way, except if you look at the DOM
here. Let's see. Did I save it up to save it first. We got we shouldn't be able to see that what's
going on the cash. Let's see. Oh, it's because I didn't put that there yet. Sorry about that.
So in order for us to use messages, we have to just like HTML, we have to create a tag for that.
So we're going to go here and where we have this div here we're going to add messages like this. Now
you can type it like this, open and close tag. Let me try to backtrack here. So basically we define
or kind of our own HTML element called messages. And we can use it by with the open and close tag
here under the app template. Now because there's nothing that we need to place between the open
and close tag we can just shorten that like this. You see what I did this is only react okay it's not
HTML usually. So messages slash I usually add a space just because it finds nice. Okay, now if I
go back and see from I should be able to see that div for the app and then message board which is from
messages form in the div there. If I didn't have a fragment, an extra div would be appearing there
if I put div here back. You see now there's
see here save it.
There's like this extra div here. But anyway, that's just a minor thing. Use what everything
is nice for you. I don't mind the extra div. But that's the fragment and you often see that as
just empty tag like this. That's just a shortcut for fragment. Okay, just like that.
Okay, so now let's fix the other stuff. So we brought the template. But now we don't have the
class applied right if you notice the style is ugly. How do you get that to be fixed?
So for the style here in HTML have the link here in the case of react all you got to do is import
that file. So we would let me cut over message.css from source I'll paste that to web client slash
source like that. So what I have to do an app is import quotes, and then I have to give the path
to the CSS file. In this case, it's in the current directory. But for react, we need to say dot slash
meaning the current directory is dot, and then slash messages dot CSS semicolon,
and save that and that should import that style, which basically is going to do an injection of
the style tag. If you go back to Chrome, and look at the head, it's basically injecting
a style tag here with the CSS. Now that's all done behind the scenes, we don't have to know how that
is achieved. But behind the scenes, there's something called a bundler that takes care
to bundle everything together and make it just work off the bat. Create react app uses webpack.
If you ever hear that term webpack, that's what's being used. And there's one of the
loaders that allows you to import CSS files, just like that. And in this loader, basically it injects
a style tag with the CSS content. It's all like automated for you. So you don't have to worry about
that. Okay, going back, we got the CSS. Now how do we do the JavaScript part? Now, this is different
now. Since we're doing react, the JavaScript is already in the JavaScript file. So we would have
to basically write the code within the function here. Let's see what we did for JavaScript for
messages. So we got some messages to show. Okay, so we have this array messages with
objects, and each object has properties that contain the message we want to show.
And then we are doing a loop here to go through each of those objects, and then build a div that
has that message, and then the class message list item. How do we do that? React? Well, that's easy,
actually, you just got to go to where the message list is, and you can just declare just like HTML,
I have a div with the class message list item, like this. And then we have some text inside that
will be message dot message. So we can just say message dot message here. But we got to do some
stuff before that works off the bat. First is when you have class here in react, we got to call it
class name. Why do you have to change that? Well, the JavaScript programming language introduced
a keyword class, so you can build classes. If you ever hear about object oriented programming,
that's what it's about. So in order to avoid clash of that, you can just say class name there. Now,
obviously, it's going to work if you don't do that, because there's probably something behind the scenes
that gets around that. But usually, you should put class name. Okay, and now it doesn't know what
message is. So we got to do a loop here. How do we look in react within the JSX? Well, we have to do
a mapping operation from the array of objects to an array of divs. Yes, so we're going to generate
divs. But I have to explain to you what mapping is. So let's go to the dev tools to the console tab.
Let's go here. Let's start off with a list of numbers. Numbers equals an array, let's say two,
three, four. So let's say I want to make each of these numbers multiply by two,
so and create a new list. That's called a mapping operation from one to another one thing to another,
it's a transformation. So I can do numbers dot map. So it's a function call. And this function
expects a function as an argument. You can put a function definition there. And the parameter here
will be the actual number. And then from this, you can return whatever you want. You can number times
two. And you got this new array with four, six, and eight. So each element was doubled.
So what the heck is going on? Well, numbers is an array. And this array has a function that we can use
called map. And it expects a function. So what's going to do is it's going to go for each of these
elements. I will call this function that you provide. And number is going to hold the current
element in the first time it's going to be two. Therefore, it's going to return two times two.
And that new value will be placed in a new array, like this in the same position as the corresponding
one. So we add four. And then the next time it called a function again with three. So three times
six, three times two is six. So six is added to the new array, and so on, right? The next one is
going to be number four. So four times two is eight. And you get a new list. Okay, so that's
what we're going to do except we're going to generate new divs from the object. So basically
going to have the messages, right, with objects inside, right? The object has a message, hello,
like this. Oops. And then another object of another message world. So we're going to take that.
Remember, it's an array of objects. We're going to just map message dot map function. And
you can give any name to the parameter. I usually give the name whatever whatever the element means
message, let's say message object. And then here we're going to return whatever we want as the new
thing. So you can see it's undefined there. So let's say we return message object dot message,
that's going to generate an array of strings, but actually we're going to return a div
like this with the message there. That's what we're going to do. Obviously it's not going to
work here. So we got to go to the react components. So let's go back there. So we're going to go here.
And we're going to do that operation. Now this return here is whatever I have here already. So
we're going to have messages dot map, the function message object. Let me just call that message
here. And then we're going to return something that's the div. And I already have that here.
And then I put the syntax. Let me fix the annotation. See the annotation is important,
otherwise kind of messy to see. And usually we add the parentheses for the return. So it's easier
like this indent, indent, indent, indent like that. And then this one there. Now because we're in JSX,
we have to add curly braces before and after that statement. Otherwise it doesn't work.
And then it doesn't know what message is. So we would go here before the return,
break a new line, but still within the function, you want to copy the definition of messages
here, put it there.
Like so, you can also put it outside the function works as well. I think it's better outside.
But we're going to change that eventually. That's just dummy data.
Now, once we get that, let's see if it's working.
So you can see we got hello world not a message and hey, up here. And if you look at the console,
there's some errors saying that each child in the list should have any key prop. And this is just
a complaint while we react that whenever we have a mapping operation, always make sure that to add a
key property, a attribute to the thing you're mapping here. So you have to add a key with
something unique. For example, message.id is the unique part. Something that changes for each
of the elements. If you recall, id is unique to each.
Okay. That makes sense. So in React world, we just can write the declarative way and we can embed some
JavaScript mapping here if we need to create new things from an array.
Okay. I think that's it for that part. Now, how do we do the actual
adding a message to the list from the text area? Now, that's a bit challenging.
So if you recall in vanilla JavaScript, what we did was
we type something here to the text area, you click write message. Now, this is a form.
If you recall here, we have a form. When you click write message, that's the submit button,
button type submit. It calls the function add message. So add message here in messages.js is called
and prevents the default behavior so it doesn't reload the page. It finds the text area by id.
It grabs the element here. This one is just to check if it exists or not.
The text area. If not, it doesn't do anything. So it calls this function add message to list
with the value of the text area, which is what the user typed. And add message to list,
a definition is to create a new div, a set the text content to that value that was typed,
and then add a class to that new div and finally inject the div into the list container,
which is this one with all the kind of rectangles. Now, the react way for that
is first, let's see here, we have to find a way of knowing what the user typed for the text area.
And to do that, we have to control this input and hold the value in a JavaScript variable.
Now you could do the vanilla JavaScript way, which is get element by id and then get the text
element, text area element dot value. But that's not the react way of doing things. The react way
is you got to go here. Okay, we got this text area, we need to control it. So we have to pass
two things versus the value. And the second is the own change for the handler function
of the event, whenever you type something in the text area, it will cause an event called change
event. Now in vanilla JavaScript to handle events is own change lowercase, and then you pass a
function name here, right with the parentheses. But the react way is you have to use camel case for
the name here. So you have to have the C capitalized. And then the equal sign the right hand side has to
be with these curly braces. And then you have to pass a function name without parentheses.
So in this case, let's say on message change. And I have to define this function here outside
before return. So I function on message change like this. So it's different, you don't need parentheses
here. And you have to use curly braces. But you might notice why did you use
quotes here for ID and the name attribute. Well, that's actually implicit. I actually have to type
curly brace there for the syntax for react JSX. But because if the value is a string, you can omit
them and just put the double quotes. In this case, this is not a string at all. It's the name of a
function. It's not a string, right? It's not double quotes. Otherwise, it would be literally that
sequence of characters. Anyway, for the value here, we're going to store
some let's say new message, a variable that we have to create. So we got to go here up
and say new message or something for now. Okay, let me put hello here. So you see it's going to appear
there. Save it. Let's take a look. I see hello appearing there. But nothing is going to happen
if you type. Okay, because we got to change things. We are now in charge of controlling how
what's going to happen when I type a character here. So we have to literally change the value of
the variable new message. But you might if you're you might be tempted to do it like this.
When I click on message change, I type new message.
Whatever new is typed, but this is not going to work.
You can see if I type nothing works, because the react doesn't know about that variable. So the problem
here is with react. So when you have to keep track of a value, react needs to know about it.
Otherwise, it will not react to changes in the user interface. So we have to keep a state, a react
state. So whatever we type in the text area has to be stored in the react state. So react keep
track of what you're going to type there. Now, to do that, we're going to go to the definition
of the variable that holds what these are types here. And we have to call what's called a react
hook. Okay, that hook is called use state. So bear with me. So we're going to say react.use state.
It's a function. And we're going to pass the initial value. So use state is a hook
that allows you to keep track of a value. And the value initially has, if you pass something here
to this function use state, that will be the initial value. Okay, now this whole thing is a
function that returns something that something is an array of two things. The first element is
the value itself. The second is a function that you can call to change the value.
Okay, so if you need to change the value in the react state, you need to call that function.
You might hear the term mutating the state, that's the mutating function,
mutate function. Okay, so because of that, this new message variable will be something like this,
like hello at the first element, and some function to change set new message
like this. And there's a definition there that would change this value here if you type like
set new message, the world that will change that to world. Okay, because of that, you would have to
say new message sub zero if you need to access the value. And you have to say new message sub one,
which is the second element in the array to access the function and you can call it
with the new value. But this is ugly syntax. So people don't use this, what they do is they
extract the first element into a new variable, and the second element which is the function into
a second variable. Okay, so you're going to see this a lot. And to do that, the notation is like
this, the cost of the square brackets surrounding the thing. And there was two values, new message,
and then set new message like this. So the first one is extracting the first element into the variable
new message. And the second is extracting the function, which is the second element into the
variable set new message. Okay, now with that, whenever we change type something to the text area,
it's going to call the functional message change here. So all you have to do is call set new message
with this value. So let's do that. So we're going to just set new message, parentheses, whatever
value the user type, which we don't have yet, right, we're going to teach you how to do that.
But let's just try that. So I'm going to click here, type a, and a change to whatever new was
typed, which was the value passed to set new message here. Now, obviously, that's not what I
typed, I typed a so we want to correct that. And in order to fix that, we have to look at the event
object. So here we're going to put event parameter. And then to access what the user type, we can do
event dot target dot value. So event object has a property called our target. And it accesses the
text area itself. And the text area has an attribute value, right, so we can say dot value.
If you recall from objects, that's pretty much what's happening here, you're accessing the attributes
of an object, the property of an object with the dot notation. Remember, the right hand side belongs
to the left hand side. Finally, let's test it again, we change the code, we always want to test it.
Let me type a here. There you go. Now we have a B, I'm going to type C. Now it's correctly
showing it every time a time character. Okay, let me show you the DAB tools,
how to debug this. So you can see what's actually happening in real time.
So I click social stab in Chrome, Firefox might be debugger, control P.
And we're going to do, let's see, what's the name of the component file, app.js, right? So we're
going to look for app.js there. Enter. Now here's the source code for that. And we're going to, okay,
I want to know what's happening when I press write message. So when I press write message,
it's a form, right? Submission.
This is the, let me see, I think that's, might be the wrong thing there.
That's not what I want, sorry. When I type here, we're not in the submission yet. So when I type
here in the text area, it's calling on message change. So I have to go here, this is the function,
I put a break point here. So that means I want the program to stop here, when that function is
executed. So if I were to type a, it calls this function here, so it stops the program there.
So you can inspect what's going on. If you hover over event, this is the event
object that has all the information. And if you look at target, the value is the text area itself,
if you see highlight there. And you can expand that target. And there's a value. If you click the
value, it's what the user typed. Okay. So that's what's happening here. If I look at,
let's see if I can see what's new message is. Let me see.
Tried it. I press control back tick. So you can also type JavaScript here, like event,
event.target, see a point to the text area, event.target.value. You can also do that if you
don't like just pointing the mouse around. See if this is working. Yeah, usually it doesn't work here.
See. Anyway, you can press play to keep going. And once you're done debugging,
remove the breakpoint. So that's how you debug a react. Just the same way as JavaScript, you just
got to find the right file there. Anyway, with that out of the way, let's just quickly do the
let's see, I guess, submission. So for the unsubmit, we got to change things, right? JavaScript,
we have to use camel case, capital S. And we need the curly grace, no quotes. And we don't call the
function here, we have to remove the parentheses. So we just have the function name. And then you
define the function outside before the return, don't define it inside the other function here,
okay, has to be outside that body, and add message event like this. Now let's copy what we did,
let's see what we did for previously, just back in track to messages, just that would pretty much
prevent default copy the value that the user typed and add message list, which would create a new div.
And then you would clear the text area. Okay, in react is like this. So okay, how do you find
what the user typed? Well, we have the variable new message. So you can just say new message and
you get whatever the user typed. Great. Now I have to add that to the list of messages here.
To the end as a new object here like this, right, ID, whatever could be for message, whatever user
type. But the problem is how do I do that in code? Well, I have to also keep track of this
in the react state. So that when I add a new message react where react to it and see, hey,
I noticed a new message was added to the list of messages. Therefore, I must update my user interface
to show the new message. When react detects a changing state, it actually calls the function
for the component again and returns the new the new view template with those new values.
Okay, so how do we keep track of messages in the state? Well, we're going to use state. So
locate the value want to keep track of and put that under parentheses
here and call react that use state. And this will be the initial value, right, the array of things.
And then because it's two things, we got a destructure. This thing is called destructuring
when you extract the first and second element, not necessarily first and second, but any number.
And usually we always call the variables name and then set name. It's just a naming convention.
We could call this whatever doesn't matter. Okay, so when I need to update my list,
I want to call set messages. So let's go down here. So I want to set messages.
But messages is an array of objects. So I must first take care of keeping the existing messages
and adding new object to the end. So to do that, I'm going to take make an array square brackets,
copy the elements from the messages that already exist to copy it, we use dot dot dot
within the square brackets and the name of the array messages. And that would just copy all of these
into this new array. And then comma at the end, you can add the new object,
which is curly brace to make an object. And then with the message, whatever the user type,
which is the new message variable here. Now you can give an ID if you want, but I would leave it
out. Probably going to complain, hey, what's the ID? So we got to figure out what's the last one.
But when we have a database later, we won't have to worry about that. Anyway, save that.
Let's see what happens. Say hello there, write message. You see something happened there.
I saw it momentarily. And we have the same problem we had before,
where the page reloads. So we have to prevent a default. So we got to go back to add message.
We got to say event dot prevent default to say hey form. I know we want to submit the traditional
way to reload a page after submission, but I don't want you to do that. Remain the same page.
Don't do that. So prevent default. Let's try again. Hello. There you go.
If I type hello to it's there. Now we want to clear this every time we add a new message. So
we can go there. After setting the messages, we can change the value of new message,
which is what the user types into the text area by saying set new message to an empty string,
which is just two quotes with nothing between. And whenever I add a new thing,
it will clear the text area.
Now it's probably nicer if you add the message to the top. It's easier to see without having to
scroll. So if you want to do that, all you have to do is move this object here before the dot,
dot, dot messages with a comma. So that way you first put the new message at the top,
and then the other copied ones at the bottom. So why does this work, right? Because when I add a new
message, I call set messages that changes the state, right? This is a state change function.
When I change the state react will call the function to render the template for the component
again. So that means the function here is called again under this template. And it will notice,
hey, messages now has an extra element at the bottom. So it's going to basically map, but now
with the messages having that new extra element at the bottom now at the top, right? So it's going
to generate that new div, including that new one. Now, what happens behind the scenes react is,
we have the live document in HTML, right? And we have the reacts keeps a copy of that.
So when you change the DOM, what's called a virtual DOM, react notice, hey,
something changed in the state. And I rendered this new tree of the document. And it has this
change. There's a discrepancy between what the user is seeing in the browser and what we are keeping
track of. So we have to make work do some work to make them synchronous. So react will change the
actual document to reflect its virtual DOM, whatever is is now the new what should be shown.
So that's what's happening behind the scenes. Okay.
So what else we got? I think that took care of pretty much all the things we got.
ABC now should go to the top is here.
Okay, so that's how we do things in react.
No comments yet (loading...)
No comments yet (loading...)
Did you like the lesson? 😆👍
Consider a donation to support our work: