Transcripts
1. Complete React Js Guide: From Fundamentals to Dynamic Apps: Hello, there, future
web developers. I'm man and Conny, your friendly instructor and guide in this exciting
react Gas journey. In this short and sweet course, we're going to build
something amazing together. But before we dive
into the project, let me tell you what's
in the store for you. We'll start with
the fundamentals, ensuring you have a rock solid
foundation and react Gas. Then we'll jump into
hands on coding where you'll build the real
world project from scratch. By the end of this course, you'll have the skills
and confidence to create your own reac GAS
applications and impress potential
employees or clients. This is the project that we're
going to build together. It's a task tracker app where users can create new
tasks using this form. When they create tasks, the task will appear
in this container. So let me show you
how we can do that. Let's say we want to
create a task one. I can press enter in the keyboard or press
this button right here. So we're going to learn
how to listen for keyboard events and how to
listen for HTML buttons event. Now I'm going to press enter in my keyboard. And there you go. The task one item was dynamically rendered or
appeared in this container. Now users can either check this item if they
completed the task. When they press this checkbox, it will turn to green, indicating that this
task item has completed. They can add
multiple task items, like task two, task three, Now, you can notice that
we have a counting here that counts the number of
task items in the list. Whenever you add
a new task item, This number right here
will increase dynamically, showing the number of
task items in real time. Now we can filter between completed and
pending task items. If I switch to completed, we will only see the
completed tasks, which in our case, only
the task one item. If we switch to pending items, we will see all the pending
task items in this container. You can delete items from here, and if you switch to all, you'll notice that the
task two item was deleted. So we're going to
learn how to delete items and render the result
dynamically to the users. You can check multiple
items if you want. Now, this application
also have two pages, the home page and
the About page. We can navigate
between these pages using the header
navigation buttons. If I switch to the About page, We will get this
simple about pate. You'll notice that the
RO path has changed to slash about. Let
me do this again. As you can see, the
UO has changed. This page contain a
small description for what this application
is all about. As you can see here,
this application is just a simple tracker
app to help you stay organized and manage
your task efficiently. It's a simple app, but it
contains a lot of features. For instance, we have
here a programming choke. We're fetching this joke
from an external API. Whenever we switch from home
page to the above page, we will fetch a new joke. We will learn how to fetch
data from an external API and render the data dynamically
inside our application. This will happen every time
you switch between pages, or you refresh this page. If you refresh it, you
will get a new choke. Now you may notice that we have a link at the bottom here
saying meet the team. If you click on it, a list
of names will appear. These names refers to the developers who worked
on this task tracker app. Now, you also notice that
the URL path has changed, and we have here forward
slash team at the end. Let me do this again and
keep your eye in the URL. As you can see, we have a
new choke here fetch it, and now let's click
on this link, and the URL has been updated
to about four Slash team. This is what we call and
reacts a nested route. Nested routes help you create nested layouts without
refreshing the web page. As you can see, this application
is full of features, and there is a lot of
things to learn here. So it contains everything you need to build an interactive
web application. We have forms, we have buttons, we can interact
with the keyboard. We can filter task items, Yeah. We can switch between pages, and the items will not
disappear from the container. So we're going to
learn that as well. You can have dynamic rendering. That's also a very
valuable feature in a modern web application. We can switch between pages, fetch some data from
an external API and having nested layouts
and nested routes. So as you can see, it may
appear as a simple application, but it has a lot of
things to offer. Actually, this is all
you need to start creating web applications
from scratch. So after finishing this course, your progress will
only depend on your imagination and
simply your CSS skills. Because this, this course will make you comprehend
what react GS is, what GSX is, how react GS
work behind the scenes, and you also learn how to create this amazing features
in a web application. Now you might be wondering
why this course is so short, clocking in at just
around 2 hours. Well, that's a great question. You see, this course is designed with your time
and learning in mind. I believe in getting you up to speed quickly and efficiently. I distort the essential
knowledge you need to master IS and build
a task tracker app. No fluff, no filler,
just the good stuff. I know your time is valuable,
and I respect that. By keeping the course consist, you'll save time and still
gain the skills to create your own RGS projects
without feeling overwhelmed. So if you're interested in building this
application with me, just enroll in this course, and let's begin the journey.
2. Course Expectations and Prerequisites Overview: Hello, their future
react developers. Welcome to our course on Complete React GAS Guide from fundamentals
to dynamic apps. In this exciting journey, we'll dive into
the core concepts of react and explore
how it plays hand in hand with Java Script to create stunning
user interfaces. So let's get started.
First thing, third. Let's understand what
react is and why it's garnered sax immense popularity in the world of
what development. React is a powerful Dava script
library that empowers us to build captivating user
interfaces with ease. But here's the kicker. React doesn't work in isolation. It's tightly integrated
with Dava script. React harnesses the
magic of JavaScript under the hood to bring our
user interfaces to life. This means that having a solid grasp of
JavaScript concepts is going to be incredibly helpful as we journey
through this course. Now, before we jump in into
the exciting word of act, let's quickly cover
some prerequisites and tools you'll need to make
the most of the tools. If you're already
familiar with HTML, CSS, and JavaScript, you're
off to a great start. These foundational
languages will come in handy as we explore
Act capabilities. As for tools, we'll be using
Visual Studio code for our coding adventures and no
DS to run our applications. You don't need to have
any experience with NGS. The only thing that
is required is to stall NogS from
its official site. Now, don't worry if you're
new to these tools, will guide you every
step of the way. Now, I'm sure you're
curious about why act is used so extensively
in the real world. Allow me to share
a quick example to fuel your motivation. Imagine you're navigating a dynamic website
with a plethora of interactive elements,
buttons, forums, animations. These elements need to respond quickly and smoothly
to your actions. This is where react chimes. It's efficient rendering process and clever use of
the virtual dom, ensure lightning test
user experiences, making react an ideal
choice for crafting, engaging, and responsive
tiplications. So there you have it, a sneak peek into Watson store for you
on this ex journey. Get ready to unravel
the mysteries of act, dive into the word
of JavaScript, and build impressive
user interfaces that leave the lasting impacts. I'm thrilled to guide you
through every step of the way.
3. Building Your First ReactJs APP step-By-Step: Start by creating a folder
and open it in VSCO. You can name the folder
whatever you like. I named Mine Task
Tracker apsince, that's what we're
going to build. The first thing we need to
do is open the terminal. To do this, you can either click on the terminal icon here. Or navigate to the menu
and select terminal. Then click on new terminal. Once the terminal
window is open, make sure you have
no GS install. You can do this by running the following command
to check its version. If the version is displayed, it means you have
no GS installed. Otherwise, you'll need to unstat it from the
official website. Next, we're going
to run a command to create our first react GS app. This can be done using
PM, PMPM, or Yn. In this case, we'll use the
command Create React app, which is a tool that sets up a new react GS project with a preconfigured structure
and dependencies. If you don't have
Yarn installed, you need to use APX create React app and add
a custom app name. Alternatively, you can
use a period to indicate that you want to
create the reacts app in the Coan folder. I'll be using Yarn
since it's more stable than PMPM or MPM. Hit enter and let
the magic happen. The command has
successfully created a four GS app ready for us to work
with. Pretty cool, right? Here's the project structure. The SRC folder holds the
application source code. The public folder contains
static assets and the index dot HTML file is
the entry point for your app. Although AGS uses
only one HTML file, it doesn't mean we're
limited to one page. We can create multiple pages
or routes using JavaScript. Each route will utilize
JavaScript to render specific HTML code
based on the URL path. Every piece of AML
code we write will be rendered within the TF
element with the ID root. Now inside the SRC folder, we find various files with the most crucial one
being index DGS. This file is
important because it employs Dava Script
to render all of our project code into the DV
element with the ID root. To put it simple, react is like your blueprint for a house. While react Dom serves
as the construction crew that transforms that blueprint
into the actual building. It's the tool that takes your react components and
showcases them on the web, making your website
come to life. The Index D GS file, we can remove this
line right here. The report web
vitals is a tool in react used to measure and
report website performance. However, we don't need
it at this moment. Feel free to remove it along
with its import statement. Let's also delete
this file within the SRC folder since we
don't need to run any tests. Our focus is on reac TS itself. Moving on to the Abdo GS file, We found a function that
returns GSX syntax. In react, we don't call it HTML syntax is
referred to as GSX, which stands for Javascript XML. GSX combines HTML
and JavaScript, allowing you to
write UI code that's both easy to read and
powered by JavaScript. Abdo GS function is a component. Now in react, a
component is a function acting as a building block
for your user interface. Think of it like
assembling a lego set. Each lego brack is
analogous to a component. These components are
reusable building blocks that encapsulate I
and functionality, making your code modular
and maintainable. Now, after this
brief introduction to reac GS files and structures, let's run the application and see what it looks
like in the browser. In the terminal, run
the command PM start. This executes the script
defined in your package do JSON file and or the script
section with the key start. This script typically
uses tools like web pack or by bolt bundle and
transpire your code. Then this command initiates
a development server and automatically reloads the app
whenever you make changes. If Package D JM
file is new to you, think of it as a control center for your projects dependencies. It lists the external tools
and libraries your app needs. These dependencies are
managed using APM, which is like a digital
warehouse for code. By examining Package DSO file, the pers can understand your app setup and
ensure consistency. Once you've executed
the command, a browser tab will open with
the URL Local host 3,000. A local server accessible
only for your machine. You will see the GS logo spinning with some
text and styles. Now let's go back
here and remove the import statement
for the Rags logo. Remove all the GSX code inside the app
component function, leaving only the
return statement. Additionally, delete
the logo SVG file from the SRC folder since
it's no longer needed. Inside the Apo GS file, note that the app
component is a function. Each component function
in AGS should start with an uppercase letter to distinguish them from other
JavaScript functions. Now, every react
component should always return some GSX code. You can directly
return GSX such as a Dev element or enclose
it in parentheses. Now, if you're
familiar with HTML and have some knowledge
of Javas group functions, the rest of actGS will
be straightforward. Now within this Dv, let's add a text saying
hello VGS. Save the file. It will automatically
re render since the MPM start command is still running
and monitoring changes. When you save your changes
by pressing control S, you'll see the
updates in the pate. All the HTML elements have
been replaced with this tiff.
4. Adding Styles To Your React Project: We've covered how
to render SSML code using GSX syntax within
reagS component. But what about styles? In the Abdo gS file, you'll notice that
we're importing a CSS file named Abdo CSS
located in the SRC folder. This file contains
regular CSS code. While we're not
explicitly importing the CSS code into
the apto GS file, we're letting reagS
know that when it renders the AbdogS component
on the client sign, it should also fetch the CSS file and use it as a style sheet
for the component. However, for the
purpose of this course, we won't be using the
specific CSS code. Feel free to delete it entirely. Moving on to the Index DGS file, we're also importing another
CSS file named index CSS. When creating a
component in IGS, it's a good practice to name the corresponding CSS file with the same name as the
components file name. Inside the Index DSS file, you'll find styles for the body and other elements
similar to before. We won't need this code either. Go ahead and clear this file. Now, back to the Abdo GS file, we're going to introduce
some GSX elements here, but we won't delve into
CSS details extensively. After all, this is a AGS course, not a CSS course. To streamline this process, I've prepared an
Abdo CSS file and an index dot CSS file for
you to download and use. You can locate them in the resources section
of this video lecture. Once you have downloaded
the new CSS files, copy the code from the abduct
CSS file and paste it here. The code includes classes like task tracker
container and others, along with media
queries to ensure our applications responsiveness
on various screens. Repeat the same thing for
the index to CSS file. Paste the code I provided
into this file as well. I've applied styling to the
body and the root element, which exists within the
index dot HTML file. Remember, this is where all
of our code will be rendered. I've set the root
element to display as a grid with 12
columns and 12 rows. Towards the bottom,
towards the bottom, you'll find timing for the scrolling bar of
our web application.
5. Understanding CSS Scoping In ReactJs: Before we move forward in
building this project, we have to talk about the very important concept in react GS. GSS scoping, which is giving each component its own
private styling playground. It's a mechanism that ensures
the styles you define for one component want and intentionally affect
another component. When you write CSS for
a specific component, those tiles are scoped to
that components boundaries. This means that the tiles
you apply to a class within the component CSS
file will only apply to elements within that
components rendered output. We act achieve this scoping
by using a technique called CSS modules or CSS
in GS libraries. In our case, we're
working with CSS modules. All of these CSS files
are named CSS modules. When you import the CSS
file into a component, the class names
inside that CSS file get transformed in a way that they become unique
to that component. This prevents class name
classes and guarantees that your style won't plead into other parts of
your application. Imagine it like
having separate rooms for different activities
in your house. Each room has its own set of
furniture and decorations. Similarly, its react
component has its own set of styles that don't interfere with styles from
other components. This approach makes your
code base more modular, maintainable, and as prone
to styling conflicts. We can style your components
knowing that their styles are isolated and won't accidentally impact
other parts of your app. Now, as you bring components together using index to DS file, react keeps the
styling magic going. Even if you have a general
style rule in Index to TSS and a specific style
rule in abduct CSS. React knows how to manage them. The more specific style
usually takes the lead. Think of it like having a
master plan for your house. The details in each room don't clash with
the overall design. So as you dive into react, remember that each component is a building block with
its own personality. It comes with its
own JavaScript file and its own CSS file. And guess what, react, make sure that your styles behave nicely within
its component, creating a harmonious
and organized web app.
6. Understanding CSS Rules Conflict In ReactJs: Hey, let's dive
deeper into react, and it's styling magic. Mage you're decorating a room. You start with a base style. But then you add some
personal touches. React works in a similar
way with its CSS. Let's say you have a
rule in index dos SS that sets the body margin
to zero. But wait. There is also a rule in abdosi SS that sets the
body margin to three. Now who wins? It's like a friendly competition
between the two. In this show down, react follows some rules. If two rules have
the same power, we call it specificity. The rule that comes later wins. It's like deciding who gets
the last slice of pizza. If index dot CSS
shouts, margin zero, and Abdo CSS calmly says, margin three, the later
gets the spotlight. React makes sure the details in its component CSS takes
precedence over global styles. Keep in mind as you
create your react app, its component brings its
own style rules and react keeps the piece by deciding which rules should shine
in case of a conflict. But for a smooth
development experience, you have to avoid adding
styles to HTML elements directly using an element
selector, instead use classes.
7. Writing JSX Code for the Track App and Applying CSS Classes: Abdu TS file, let's replace
this div with another one. Also, move to the middle of the new div and then
return a new line. This new div will serve as the main container
for our tracer app. We need to apply a specific
CSS class to it from the Abdo CSS file called
Task tracer container. Copy the class name and
within the opening tag of the div inside the
Abdo gs component, apply the CSS class using
the class name attribute. In regular HTML, this
attribute is just named class. But in Ragas, it's class name, and remember to use Camel case. After the equal sign, inside double codes past the task tracker
container class. It's similar to
writing normal HTML, but pay attention to the
attribute name and always use Camel case for
attributes like class name. If you save this,
make sure to start the application by running
NPM start in the terminal. Then open the browser
and you'll see a pleasing blue container
in the middle of the page. This container will hold the tracker app along with
its main functionalities, and you'll also notice the
style scroll bar in the right. Please note, I slightly
increased the size of the container element on the screen using the
chrome zoom tool. Now, returning to the code, we insert a task item
within this container. Add the following GSS
code inside this div. The first div is a task
tracker item container, and the inner div is the
actual task tracker item. This will render task one
inside the blue container. As we progress with the project, you'll have a list of task items like task one
followed by task two. However, we want manually
write each item. Otherwise, we'll use tender
A steml Javascript and CSS. Instead, we'll use react to dynamically render
the list for us. We'll cover how to do that
in the upcoming lessons. Now let's focus on shaping the main structure of
our task tracker a. Just a quick remainder,
whenever we save the app file, index dot S will execute again, causing the app
component to render. The final output will
be displayed within the root element in the
index dot HTML file. This file will be served to the client when they
access our web server, which in our case is
local host 3,000.
8. Mastering JSX Structure and Comments for Clear and Organized Components: Task tracker app now requires
a form with an input field. This form will allow
us to dynamically add task items to the task
list using reacts. Remaining within the app
component will incorporate the input from inside the
task tracker container. To achieve this, add
a new DF and set its class name to
a task container. Inside the DF place
the input field in a button to add new
items to the list. However, I'd rather separate
the actual input form from the task tracker
container and keep the container dedicated
solely to the items list. To accomplish this, I'll take this dive and position it
above the container like this. Now when issue arise
in a react component, it's essential to ensure that all GSX elements are enclosed within a
single wrapper element. This practice helps react maintain an organized structure. Think of it like
packing for a trip. You wouldn't want to carry
numerous loose items. You'd place everything in a bag or suitcase to
keep them together. Similarly, in the
realm of react, we apply a similar concept. You can envelope
your GSS code within an HTML element such
as a div or section. Or even an empty
tag like this one. This wrapper element
doesn't need to do much. Its purpose is to satisfy
react requirements. For instance, if your component includes multiple
elements like headings, paragraphs, and buttons,
and encase them all within a single t
or section element. This adheres to the one
wrapper element guideline, enabling react to understand your component
structure effectively. Consider it as offering react a container to house
your GSX elements, allowing it to comprehend
the arrangement. Now suppose we wish to insert comments to clarify the
purpose of its development. When dealing with GSX, you'll note an
interesting technique. The regular double
forward slash for single line commons or multi
line commons won't work. Instead, we employ
a lever method, which is Enclose
your comment within two curly braces and employ the multiline comment
syntax within. Remarkably, these curly braces can also hold JavaScript code, labeling the addition of
dynamic content into your app. By dynamic content, I mean, altering the GSX code based on specific conditions
without reloading the app. We'll delve into how to aceive this in the
upcoming lessons. Within this section, lesson ser a comment to pass that the
dip below is a task for. Copy this comment and paste
it above the task container, Modify the name to
tasks container. And finally, add another comment to the task item container, name it Tasks item. This way, anyway,
reviewing our code will grasp the app structure
and objectives. Feel free to follow
these adjustments to enhance the clarity of
your code structure. If you have any questions, all need further assistance, don't hesitate to ask.
9. Componentizing UI Elements: Let's continue developing
our task form. To begin add an input element
with a self closing tag. Set the type attribute to text, provide a placeholder saying a task and assign the
class name attribute. Ensure not to use tases
in attribute names since reac gs attributes don't
include taxes or under scores. Class name for the input
element will be a task input. Below the input field, we'll add a Patton
labeled ad with the class name a task
Bt N. Short for button. After saving this
and making sure your app is running,
open the browser. You'll see the form, though
without any styling. But don't worry, we'll
address this right away. I'd like to pass an
important point. In the word of react,
organization is key. Think of it as building
a complex puzzle. Is piece needs its designed spot to create the full picture. Similarly, in react,
we break down our code into smaller
units called components. These components are like
distinct sections of your app, such as a header,
sidebar, or footer. By organizing our code this way, we establish a structure
that's easy to comprehend, maintain, and even we use in
different parts of our app. So remember, in react, split your code into components and watch your app come
together beautifully. Within the Korean code, we can segregate the
task form from the rest and transform it into a
standalone react component. Start by creating a
new fold door inside the SRC directory,
naming it components. The convention is to use the name components
as it's descriptive, but feel free to choose a
different name if you prefer. Inside the components,
fold door, create a file name
task formed to GSX. Note that you can use either
the GSX or GS extensions. But I'm using GSX
here to clearly denote the uses of GSX syntax. When creating a react component, it's essential to import the react library at the
beginning of the component file. Even if you don't directly
use reacting every component, it's required since
GSX gets transpiled into Java scrat code with
references to react. Now, next, declare the
function component task f. It's the best
practice to start component names with
an apocase letter. This practice distinguishes
custom components from building HTML elements and
enhances code readability. Define the function
using arrow syntax. This represents a
functional component, a more approachable way
to create components compared to the older
class based approach. Now, export the functional
component to make it accessible for use in other
components and files. This component will return the GSX code for the
task form that we originally wrote within the Abdo GS component.
And that's it. Now save everything and use
the task form component in the app component first imported from the
components folder. Selecting the task form file. Then incorporate
the component into the GSX code just like any other element with
the self closing tag. Upon saving the Abdo GS file, you'll notice that nothing
changes in the browser. This indicates that we've
successfully encapsulated the task form GSX code into
a standalone component. Now, let's apply siling to
the task form component. Create a CSS file named
task form dot CSS, which you can find in the
video resources section. Download it and include the
CSS code from that file here. Within the task form CSS, we define an a task
container with the blue background color and media queries for
responsiveness. To ensure these tiles affect the GSS code within the
task form component. We have to port the
CSS file into it. Now, it's good practice to make this port the first
thing in the file. Since we name the CSS file the same as task form component, don't forget to include
the dot CSS extension, so AGS knows which
file to unport. Upon saving this, the task form will appear beautifully
in the browser. Now let's proceed to create the task item as
its own component. Create a new file called
task item dot CSX. As always begin with an pocase
letter for the fi name. Inside this file,
start by importing the react package from react, and then declare a
function name task item using arrow syntax. Remember to export the function at the bottom of the page, either as a default export using the default keyword or as an object containing the task item component
as a property. In this case, when we import a component that was
exported as an object, we have to use object
destructuring syntax. Next, copy the task
item GSX code from the Abdo GS component
and return it as the GSX code for the
task item component. Since each component should
have its own CSS module, create a new file named
task item dot CSS. Within the CSS file, paste the code from the
resource section of this video. Then pot the task item dot
CSS file into the component. At the top of the AbdogS file, replace the existing GSX code with the task item component. You can use VS codes assistance to import it or add
the port manully. Now, finally, make this a self closing component and
save the AbdogS file. In the browser, you'll
see the task item with a white background
and a hover effect that turns the background
color to light gray. By using the components
concept in IGS, you will enhance the
development process and create a more organized
and powerful project. For example, here we
require a delete button, add a button element with the
text del short for delete, and a class name of
Task Tracker item Del. After saving this, the bottom will appear with a background. When you up the task
item component, it will be re rendered, causing the component
to re render as well. The final output will be displayed within
the root element in the index dot HTML file
within the public folder.
10. Getting Started with State Management: Exploring the useState Hook in React: Before we proceed with building the task item deletion
functionality, we need to handle
the creation of task items using the task form. This involves passing
the task content from the input field and adding it to the item to the task list upon
pressing the add button, causing it to dynamically
appear in the list. To implement this functionality, we'll develop a function within
the task form component. Remember in react GS, a component is essentially
a function where we can embed application logic
before the return statement. This logic could
involve fetching data from an API or performing
certain tasks, after which we
return the GSX code. Let's name the function a task item and use the
arrow function syntax. Inside the function, we need
to extract the input value, representing the task
content and store it in a variable that can be shared across the
entire application. In react to track and say the latest state
of the input field, we use a react hook. Hooks are functions provided
by react that allow you to interact with various aspects of component state and life cycle. Think of them as a
way to tell react, I want to do something specific when this part of my
component changes. For example, if you want to keep track of input data that
can change over time, you'd use the U state hook. It's like placing a marker on
a puzzle piece that moves. Whenever that piece changes, react notifies you
to update the view. Import the use state hook
from the react package, and now this hook returns
an array with two items. The first item represents the latest state of
the tracked data. In our case, the input value. The second item is a function used to update
the state of the data. We name it set input value, and it should always
start with set. For instance, if you're
tracking a user name variable, you'd name this
function set user name. To update input value whenever the input
field value changes, use the change attribute. Set it equal to an
open end closing c brass to write gescpt
code within the GSS code. This function takes
an event argument, which we used to
update the state of input value using the set
input value function. Rename the argument
to event for clarity. From the event, access the target property that
holds the input value. The change attribute will update input value every time a character is added
to the input field. When set input value is called, the task form component
will re render. This illustrates why the
U state hook is valuable. It triggers component re rendering whenever
the state changes. Next, we'll execute the
at task item function to save input value and
added to the item list. For now, will console
log input value. This function will execute
upon clicking the ad button. We need to listen for the click event using
the on click attribute. Place the function name
within the curly braces, and don't call it here. Instead, provide a reference
to the function name. When the bottom is clicked, the function will be called. You can use the direct
reference or define an arrow function to call the at task item function and side. Regardless of the approach, the concept remains the same. For cleaner code, use the
direct reference, like so. After saving the changes,
open the browser, lanch the inspector window and of the go to
the console tab. Let's arrange the console
tab for better visibility, and now inside the application, form input task one, and click the at pattern. While nothing happens
in the items list, we'll see the input value
printed in the console. This occurs because
a task item is executed whenever the
apuem is clicked.
11. Understanding Component Communication: Mastering Props Usage in React: Now we have to save each new task item in an array
inside another use state. We will define that use state inside the app component
because we need to use the array of items to dynamically render the list
of items in the browser. First thing first. Let's add
use state here and call it. We also have to import
the react package and use object destructuring syntax to import the Ue state
hook from react. This US state will
return an array. The first item of this array represents the array of items. We can name it task items. The second one is
the set function. Will be responsible for
updating the array of items. Now, the tricky part is
that we have to call the set task items inside
the task form whenever the at task item
function gets executed and save the newly
created task item inside the items array. But how are we going to get
access to the set task items function when we already defined it inside
the app component? Again, react comes with
a mind blowing solution. We can use something
in react called props, which is simply a
function argument. That's how a function can
normally get access to another function or variable by passing it as an argument. Function arguments
are not something new to us unless you
don't know Java script. What's new to us is the way react passes the props to
the component function. If you want to pass
the set task items to the task form component, we have to add an attribute
and name it set task items and set it equal to the actual
set task items function. This way, we will have
access to it inside the task form component through the props
object argument. Keep in mind that its property inside the prop object is called a prop and it's just a reference
to its real definition. When we call the set
task items function, we're actually calling
the set task items from within the app component. This has nothing
to do with react. It's just how Javascript works. We're not going to
save the input value, which is a simple text
to the task items, state because we want the
task items to be an array. We will do that by pushing this input value as a new
item to the task items array. But first, we need to have access to the task items array. We're going to
pass it as a prop. Add a new attribute
name task items. By the way, you can name
the prop as you like, but make sure to name
it in a way that makes sense and set it equal to the correct
variable or function. Now inside the task
form component, we will use the prop object to get access to the
task items array. Then we can use JavaScript
method called push to add the newly created
item to the array. I prefer using another approach, which is by passing an array, then adding three dots with out spaces followed by the
task items array prop. This is called the
spread operator, which spreads all the array
items inside the new array. Then we can add a
new item by adding a coma and passing the
input value state. When we click on this button, this function will be executed, resulting in updating
the set task items with a new array containing all the task items along
with the newly created one. When the application
first starts, the task items
array will be null. In Javascript, we cannot
spread or perform any array operations
on a null value. We can avoid this
scenario by setting the initial value of the
state to an empty array. The p component will
re render every time the set task items state is called from the
task form component. Can observe that
by console logging the task items array
inside the app component, then save and open the browser. Let me clear the console and in the task form at task one
and hit the at bottom. You will see that
the task items array is printed to the console. When you console log a
state in a react component, it might trigger twice
in a row when the state changes to the reacts
patching mechanism. It can group multiple
state updates together, causing the log to
fire for its paths. This is normal behavior to optimize rendering and updates. It's important to note that the exact number of logs isn't guaranteed and can vary based on the reacts
internal processes.
12. Dynamic Rendering: Building Responsive Interfaces in React: Al right. Let's not just print out the task items
array on the console. Instead, we want to take
each item from the array, display it in the task
track or container, and simultaneously update
the browsers item list to match the state of
the task items array. Whenever the state changes, the list and the GSS code
should also update accordingly. To make this happen, we wrap the task item component
in double curly braces. Doing this because
we're going to use Dava script code
inside those braces. We'll be using the map method, a hand Gray function
in JavaScript. With map, we can look through the task items array and interact with each
item individually. Inside the maps
callback function, we get access to each task item. This lets us create a task item component
instance with specific data. This dynamic rendering strategy gives us a bunch of components. It's representing a unique
task from the array. What the math
function produces is an array of g Sx elements, each corresponding to an item
in the original data array. If we save this and take
a peck at the browser, we'll see that two task items have been rendered in the list. That's because well, our
array only has two items. Now, if we add another item
through the task form, a new item will dynamically appear at the
bottom of the list. However, the content of these
items isn't dynamic yet. To make them dynamic, we're going to use props and pass the task item
to the task component. We'll swap out this
with the task prop. If I write it just like this, it will show up as plain text. But if I encase it in
a double relate brass, it will be treated as
a javascript variable and replaced with
its actual value. Every time a new
item is created, it will join the list
with its distinct value. All thanks to the map function, which generates an array of task items component elements. Whenever the task
items array changes, the component gets a rerun. Triggering the map function to re run and generate
the array of items. An each list item
is called child. Now, if we clear
the tasks list by reloading the page and
try to add a fresht item, you may notice that an or
in the console telling you that each child analyst
needs a unique key prop. Here's how we can fix it. We can add the key prop to the task item component
as an attribute. It should be a unique key, either a number or string. Can use the index parameter
of the map function, which will give each element a different key than the others. In react, when you
dynamically render a list of components using the map
function or any other method, each component needs
a unique tifier. That's where the
key prop comes in. The key prop is a special
attribute that you attach to each dynamic
rendered component. It's a job to help
react distinguish each component uniquely
and efficiently. This is especially useful when changes happen in the list, like adding, removing
or rearranging items. When you make changes
to the list of items, react relies on the key prop to figure out which
components have changed, need to be added or
should be removed. This smart approach reduces unnecessary updates and makes the whole process
smoother and faster.
13. Managing Tasks and Dynamic Interaction in React Web App: After rendering items inside the task tracker container list, it's time to work on the task
item component and make it possible to delete an item from the list using this button. Now, this button will delete an item from the
task items array, since we're using
that array to render the task item nests
in the app component. We need to define the
function that will handle the deletion of the
item inside the app component. Inside here name the function, delete item by ID. Use an out of function, that will take an ID argument. Inside it, we will update
the task item array, state using the set
task items method. First, let's prepare the
new version of the array. Let's declare a constant
a name new task items, and set it equal to
the task items array. We will use the filter method to iterate through the
array items and only return items with
an ID that doesn't equal to the ID of the
item we want to delete. The filter function will return a new array that doesn't
contain the delete item. We will pass the new task items array as the new state
of the task items array. Now we have to execute the
delete function when we click on this delete button inside the task item component. We will pass the delete item
by D function as a prop. Then inside here,
we'll listen for the click event on this button and execute the delete
item by a D function. Now instead of
every time we want to access a specific prop, we have to write
props dot something. I'd rather use
object destructuring to extract the props
from the prop object. By doing so, it becomes clear what this component
will accept as props, and it's more
organized this way. Now, if we save this and
try to delete an item, nothing will happen
because we didn't pass the item ID to the delete
item by ID function. As you know, we can't call the function directly
like this because we have to pass a reference to the function
without coning it. Otherwise, it will be called every time the
component renders. There are two ways
to pass the ID. First, we can utilize
the band function, which accepts this context. Now that this keyword in
Java script refers to the object that the
corrient function or method belongs to. It represents the context in
which the function is called and helps you access properties and methods
of that object. The second argument is going to be the actual
function arguments, which in our case is
only the task item. This is a very complicated
way of doing a simple thing. I prefer adding an RO function like this and just
like we did before, and call the delete item by ID function and pass
in the task ID. By now, we don't actually
have an ID inside the task prop because we're saving its task item
as a plain text. We have to update this before we continue by replacing this with an object containing
an ID property set to a dynamic value. This dynamic value will
be a simple operation, which is the task items
array length plus one. Then we can name the
second property text and set its value
to the input value. In this way, we can delete task items from the
array using their IDs. Now the content of the task item is inside
the text property. Make sure to update
that. Now, let's save this and
inside the browser. We have to reload
because we have updated the shape
of the task items. Now let's add task
one, then task two. Before we delete the items, let's go back to the code inside the app component
and console log the item ID just to have a closer lo at what's
happening behind the scenes. Let's delete task number one. You'll notice number one
was printed to the console. If we delete task number two, the number two will be
printed in the console. Now, this shows you how Ya
can be flexible and dynamic, which opens the door
for developers to build exciting and
interactive web apps. Now inside the task form, let's extract the props from the props argument using object destructuring and
update the component. Now, I want to highlight
something important here. If we try to add an
item to the task, it will work fine. But if we leave the
field empty rest ad, the item will be added
to the item list. We have to prevent
that from happening. And that's by adding a
checking block inside the ad task item function before we update the
task items survey state. If the input value is
equal to an empty string, it will just plug
the execution of the code using the return
statement like so. Now it will work fine when
we pass an empty string. But when we add the space as a value and press the at putton, the item will be created. We can simply prevent that as well using the trim function, which removes any
spaces from a string. If the input value only
has a space inside, the trim value will
return an empty string. That will fulfill this
if statement condition, which will result in blocking the execution of the code and preventing the creation
of empty task items. Now, in most modern
web apps like Google, for example, we
don't need to click on the Search button
to execute the search. We can just press Enter, and it will do the same work. In our application, we can do the same thing by listening
for the keyword event. When the enter key gets pressed, we execute the A
task item function. We can listen for that event on the container element using
on key down attribute. You can listen for the
event on any GSX element, but it's always better to put
it on the parent element. This attribute
requires a callback that will accept an event. We can use that
event to check for the key name that was
pressed by the user. If it is equal to enter ten using the Javascypogical
end operator, we can execute the at task item. Now, let's say this and
test it in the browser. At task number three, and hit Enter on your
keyboard. There you go. It's so much easier this way. Now we want to add
one more improvement to our task form component. I want to clear the input field whenever we add a new item by pressing the at button or pressing the enter
button on the keyboard. This one is also super easy. We just have to come here after updating the task items
array and then update the input value using the set input value function and set it to an empty string. If we test this in the
browser, it won't work. But if we cons log the put value state here
and in the browser, we start typing, you'll
see the state of the put value changing every
time we type something. Pay attention when
I hit the erkey, we will see that the last state of the input value is empty. It's actually working, but it doesn't have an effect on
the input field because we didn't connect the
input value state to the actual value
of the input. To do that, we have to set
the attribute value of the input element to be equal
to the input value state. Now, if we try to create new task and then hit
enter or the abuton, the input field will be cleared.
14. Creating a Dynamic Checkbox with Visual Indications in React: Top of deleting task items. We need to create a
button that functions as a check box to mark a specific
task item as completed. For this, we'll add a span element to
serve as the button. Yes, we can achieve
this because in react and Java
script in general, we can listen for the
click event of any element so that we can turn that
element to a functional button. Now, let's include
the word finish. For the class name, use the check mark class. By clicking on
this span element, it will set the state of this
task element to checked. We do this using the state hook. Make sure to port it at
the top of this file. Then we'll name this
state is checked, and the second argument will be named Sets checked function. We'll listen to the click
event on the span element and execute a function called
handle check box change. This function doesn't exist yet, so we need to define it. Side here, we can
update the use checked state to be true and set
the initial state to force. In this case, the user can mark the task item as completed. However, if they
change their mind, they cannot update the
ease checked state. As every time this
function runs, it will set the ease
checked state to true. We don't want that to happen. So we want our finished button
to function as a switcher, like a normal check
box where you can check or and check it by
pressing the same button. To achive this, we can update
the state value by adding an exclamation mark and passing in the ease
checked constant. This slosical
operation will always return the opposite value
of the Korean state. If it is true, it will become false so that if it is checked, it will become unchecked. If we try testing the
finished potent now, it will work, but we won't
notice anything visually. Let's replace finish
with k first and rub it inside a span with
the icon class name. Now, the icon class name
won't have an effect for now, but that's all right because
we'll replace it with an actual icon in the
upcoming lessons. Now, how do we add
some visual cues to represent the state
of the checkbox element? Well, with RacGaS,
we can achieve dynamics swing by using
the style attribute. This attribute is used
to add in line sting. Place two curly braces
and provide an object? This object can contain
any CSS property. Normally in HTML, we set
this attribute to a string. However, in reagas, it
should be an object where its CSS property is
a property of the object. In our case, we'll use the background color
property and make its value dynamic by utilizing the ease checked variable state within a t ternary operator. When it's true, we'll set the background color to
the following color code, and if it's false,
we'll set it to white. Save this and in the browser, click on the k button. You'll notice that it will change its background
color to green. Clicking again, we'll
return it to white. You'll notice a
smooth transition between the two colors due to the transition property within
the check mark CSS class. This property will take 0.3 seconds to transition between the two
background colors.
15. Enhancing Task Completion and State Management in Your React App: Inside the task item component, we've created the ease
checked state and are only using it to update the background color of
the check box element. However, we haven't yet developed
the main functionality, which is marking the task item as completed and updating
the task item state. To achieve this functionality, we need to define a task
completion function in the component. This function will
take two arguments, task ID, and is complete,
a bullying argument. We'll pass this function as a prop to the task
item component. Inside the handle
checkbox change function, we'll execute this task
completion function, passing in the task ID. For the is complete argument, we'll use the ese checked state and add an
exclamation mark. Now, moving back here, when we need to update
the specific task item, we have to update
the entire array. Instead of updating the array outside the set task
items function, as shown here, we can
do it differently. We can pass in a coback provided by the previous
task items array. This callback should
return the new state, which in our case is an array. Next, we'll iterate through the previous task items array
using the map function. For each task item, we check if its ID matches
the task ID argument. If it does, we'll
return an object and spread the old task properties
using the spread operator, which works for objects as well. But just make sure to spread objects into objects
and arrays into arrays. We'll then add a
new property called completed and set it to true. When creating the
task item initially, we should set the completed
property to force, ensuring all task items
start tasked and completed. Now, let's head
back here and add the task completion prop to
the task item component. To sum up, when we click
the checkbox element, we trigger the handle
checkbox change function, updating the ease checked state and changing the checkbox
background color. Subsequently, the task
completion function is called with the task ID and
is completed arguments. This function executes the
set task items function. Updating the task items state and marking the target
item as completed. By the way, if the task items ID doesn't match the
targeted items ID, it's returned to the array
without modification. Regarding the
completed property, instead of setting it
to true like this, it should be set to the value of the is complete argument. This way, we can switch between checked and unchecked states with just pressing one button. Let's log the task items array to better understand
what's happening. Now open the browser, make sure the server
is a running first, then add an item task one. In the console, you'll
see the task items array containing the task one item with the completed
property set to falls. Clicking the k button sets the completed
property to true. The presence of
two arrays printed here is due to the
nature of reacts, which sometimes re renders multiple times depending
on component state. If it renders two
times it's normal, but more than two or three
times could indicate an issue. Now, I'd like to
address an issue in the app that may be an outset. When adding a few items, then deleting and
checking an item, adding another item task free, then check that item
and then and check it, and then trying to
delete task number two, both tasks get deleted. This odd behavior arises
because we shouldn't pass the items array prop from the task form component and use it inside the set task
item state function. This manipulation of state leads to unintended
consequences, including the simultaneous
deletion of multiple tasks. Now, to address this, we need a more controlled approach
to state management. We can cut this code and add a coback to the
set state function, utilizing the prev argument containing the
latest state data. We'll then return and
paste the array there. Instead of using the
task items prop, we'll use the Prev argument. This ensures we're always
working with the latest state. Now, give this a
try in the browser. Clear the console at
task one, a task two, then check or check items, and when deleting
a specific item, only that item will be deleted.
16. Getting Hands-On with useEffect Hook: Adding Filters and Dynamic Styling: Our react application is
taking its final shape. We can create new items, we can mark them as
completed and delete them. Now I want to add
an element inside the striker app container and render the Korean tasks
count to the user. This will enhance
the user experience. Inside the app component and inside the task
tracker container div, we'll add an info bar element. First, add a di and set the class name to task
tracker info bar. Inside this dif, will add the span element and render
the task items way length. Now in the browser, if
we have an empty way, we will get zero items. Whenever we add another item, the number will
increase and it will show us how many items
we have in the list. Now inside the info bar, I want to have some buttons to filter the task items
by their state, so we can filter the completed tasks and
render them alone in the list or filter the pending tasks and also
render them alone in the list. Inside here, let's first add the span element and
add the text all. This will be utilized to remove the filter and render all
the items inside the list. The second clickable
element will be responsible for showing
only the completed tasks, and the last one is
for the pending tasks, the tasks that are not
marked as completed. Now we are going to handle each filter type
using a Ue state. We will have a filter type state and the corresponding
set function. Inside the U state
function itself, we will set the initial
filter type value to all. If there is no filter applied, we will render all
the task items. When we filter the
task items away, we should save the filtered
result to another use state. Otherwise, if we modify the
task item state instead, the original data will be lost. Name this new state
filtered tasks. Let's begin by handling
the filter type state. We'll add an onclick
event listener to the all element and execute
the set filter type function, and set the state to all. Next, copy this and paste
it to the completed button, and change the
state to complete. Do the same thing here and change the filter type
state to pending. When we update the
filter type by clicking on one
of these buttons, we will filter the
task items array and save the output to the
filtered tasks array. So instead of rendering
the task items way, we have to render the
filtered tasks array. And when we click
on the O button, we will update the filter tasks array with the
task items array, which contains all
the created items. The task items way state is
going to work as a storage. Now, how we're going to update the filtered task array when
the filter type changes? Well, in react, we can use
another ho called use effect, which is a powerful tool
in reacts for handling extra tasks that need to happen when something
changes in your app? We have a list of
tasks that we want to filter based on
different criteria. When you use use effect, you can automatically update that list whenever
the filter changes. It's like tending react
to keep an eye on certain changes and then take specific
actions in response. In our case, we use use effect
to watch for changes in the filter type and update the filter task
survey accordingly. This keeps your app responsive and in sync with users choices. Now, the user effect hook
accepts two arguments. The first one is a coback that will hold all the
code we want to run. The second one is the
array of dependencies, which is like a watch
list for changes. You put variables in there that you want to react
to keep an eye on. When any of those
variables change, the code inside use
effect runs again, or in other words, the user effect coback
will be executed. It's a way to say, Hey, react, if these things
change, do this stuff. If you leave the array empty, the effect runs once when
the component starts. If you remove the
array entirely, the effect runs every time
the component updates. In our case, we
want to watch for the filter type state and
the task items array, so that every time we have
a new item in the array, we run the filter
functionality again. Now inside this callback, we'll check if the filter
type is equal to completed. Then we will update
the filter tasks array using the previous argument
and the filter method. Then return only the items with the property completed
equal to true. Else, we will reset the filter task array to the
original array. This should be set filter tasks and pass in the
task items array, which contains all
the task items. Now let's save this and test
it out from the browser. Ops we have an order, and that's because I set the initial state of the
filter task array to a string, but it should be an empty array. I copy it from this line
and I didn't update it. Now let's save and
go to the browser. The order has disappeared, and now let's add
a new task item. Then add task two. Let's mark task
one as completed, and when we click on
the completed pattern, you will see that the
list gets filtered, and it will only keep
the completed tasks. If you click on the O Paton, it will render all the items. Well, it would do the
same thing when you click on depending filter because
we still didn't code that. Let's add the code to
filter depending tasks. Here, add an LF statement. We have to check if the filter
type is equal to pending. If so we will update the filter task array state and do the same thing
that we did here. Copy this code and
paste it and only return items with completed
properties set to false. But now by using the
previous filter tasks array, we will filter an array
that was already filtered. This will result in
a weird behavior and the pending
filter will not work. On top of that, things
will start to break down. What we need to do here is to filter the task
items array itself, because as I said many times, this array state will always
contain all the task items. Let's copy the filter
callback from here and update the filter tasks array with
the new task items array. Copy this entire code, and let's do the same thing
inside this if statement two and just change the
completed property to false. Now inside the browser, make sure to reload the
paste to reset everything. Then add task one, task two, and task three. Let's check task one. If we filter the
completed tasks, we will only get
task number one, which means it works. If we click on pending, we will get depending tasks. But task number two
is checked now. But when we remove the
filter by clicking on on, the check mark will disappear. This is just a rendering issue, which means when we
play with the filters, the task item component is not getting rendered correctly. We can fix it by going to the task item component
and add a use effect hook. Make sure the import
it from the I package. This use effect
hook will watch for the task dot is complete
and is checked variables. And when one of them changes, we will update the
use checked state. Save everything and go
back to the browser. Now, if you switch between
completed and pending filters, you will notice the
task item components are rendered correctly. To avoid such errors
in the future, just make sure to use the
use effect hook if you have any GSX elements that rendered
based on a condition. Now, before ending this video, I want to add something. Currently, when we
switch between filters, we can't know the
current filter type by just looking to the UI. What I want to do here is to highlight the
active filter type. We can do that inside
here by autorizing the style attribute to
add some dynamic styling. We will update the
background color based on the filter type. If it equals to completed, we will use the end operator and return this gray background. This actual should be
all not completed. Copy this style attribute and place it inside the
next pan element, which represents the
completed filter and change all here
with completed. Add another equal sign here in order to make it a
logical operation. Finally, let's do the same thing for the bending filter pattern. If the filter type
is equal to bending, well chang the background
color to the color gray. If you save this and have
a look to the browser, we can see which filter
type is activated.
17. Getting Started with React Icons: Elevate Your UI: The task item component. I want to replace the content of the checkbox element and the delete button with
some beautiful icons. In react GS, we can stall and utilize a package
called react icons. Instead of creating these icons from scratch and
searching for images. The react icons
package gives you a wide array of icons
right at your fingertips. You can use PM install or Yarn ad to stall the
react icons package, then head enter and wait for the installation
to complete. You can navigate to
the official site of react icons using the C RL. There you will find
instructions on how to install the package
and utilize it. On the left side of this page, you'll see a list of
different icon libraries like Font Awesome material
design and more, all within one package. Inside this search bar, you can look up a specific icon. In our case, we
want a delete icon. I'm going to type delete. This will give me a list of
delete icons to choose from. You can pick anyone you like. For me, I'll choose this one. When you click on it, the name of the icon will
be copied for you. Now you can go back
to the project on top of the task
item component, right and board, and
open two curly braces, then paste the name
of the icon there. We will import this icon from the a icons package and
from the AI folder. You can see that we have
a lot of folders here, but you can know which
one your icon is in by the first two
letters of the icons name. Next, we need another icon
for the check button. I'll search for check, and I'll pick these two icons. In the project, I
will switch between them according to the
East checked state. If the task item gets checked, I will render the filled icon, and if it gets unchecked, I will render the
empty checkbox item. Let's go back to the project and inside the task
item component and pot both icons in a separate port
statements like this. Now let's start with
the delete button. Remove this text and add the AI outline delete icon
just like a react component. Now, if we save this and
check in the browser, we will see the icon
was rendered there. But it needs some stying
to make it bigger. Go back here and add
a class name, icon, which you can find in the task item CSS file if you
want to have a look at it. Now this class will make the
delete icon appear bigger. Let's go back to
the check button and delete this pan element. Instead, we will render
the BS check square icon. It also needs to have
the class name icon in order to make it
bigger like this. Now, if I click, you'll see the background
color changes to green, but it's actually the background
of the icon container, not the icon itself. I want to switch between this
icon and the filled one. So In the project,
I want to switch between this icon
and the filled one. Let's add it here,
then grab both of them inside two curly braces because we need to add a
Java script code. We will check if
the variable state is checked, is not true. Which means the item
is not checked. Then we will render this icon. Otherwise, we will
render the filled icon. Now in the browser, if I
click on the checkbox icon, it will be replaced with
the filled checkbox icon, but we don't want it to be
filled with the color black. We can change the
fill color using the fill attribute and set
it equal to this color code, which is a light green color. But now in the browser, it appears like it disappeared. But it's not because
the background of the element is green too. That way we can see it. To fix that, let's remove
this style attribute from here and this time you can
see the fill checkbox there, and it works like magic. Now, I also want to change the delete icon with
the filled one. Let's search for the delete
and let's pick this one. Because it starts
with the letters AI, we can import it
from here as well. Then scroll down and let's replace it with
this icon here and set the fill attribute to the color red because
it's a delete button. Finally, let's
remove the old icon from here and check the
browser. All right. We can't see anything
because again, the background color is red too. We have to change that
from within this class. Open the task item to CSS file. And remove the background
color property. Now we can see the delete icon. As you can see, using icons made our app more beautiful
and fun to use.
18. Adding Multi-Page Navigation: Implementing React Router DOM: Task tracker functionality
is completed. Now we will focus on
adding multiple pages, or in other words,
multiple routes. To do this, we will first
add a header at the top of this page and then add some
navigation links to it. In the components folder, we will add a new component
and name it header g SX. First, port react from react, then define the header
component function and export it at the bottom, Inside this component,
we'll return a header element and give
it a class name of header. Inside, we will have
two navigation links, one for home, and the
other for an about page. These two elements will have
the class name header item. We still don't have
these classes yet. We will create a new CSS file
for the header component. You will find this file in the resources section
of this video. Just add it to your project. It has some styles for the header element and
for the header items. Now, the header component
is going to be added inside the index CS file because we want the header to be
present on all pages. Inside here, add header and make sure you import it from
the components folder. If we test this in the browser, we can see that the Hader is there at the top of the page, but without any styling. That's because I forgot to unpot the hydro Dot *** file
inside the header component. Now, if we check again, we will see the header with home and about
navigation buttons, and equal ho effect. Now, the home page in our
case is the ab DGS component. What we're missing
here is the at page. We're going to build
a component for it and name it about DGS X. Again, port react from react, then define the component
function and name it about page and export
it at the bottom. For now, let's just return a
dip with text saying about. Now inside the Index doziS file, go ahead and use the a
page component like so. In the browser,
you will see that an a text was rendered there, coming from the about
page component. We don't want the
about page to be rendered with the homepage
at the same time. We want each page to be
rendered in a separate route. For example, if we navigate
to Local house 3,000 slash a, we should get only
the about page. Now, when it comes to building web applications with react, you may have noticed
that by default, react supports a single
page application approach or in short terms SPA. In SPAs, everything initially loads on a single HTML page. As users interact with the app, react updates part of
that page dynamically, giving the illusion
of navigation through different pages without actually refreshing the whole page. However, there are
scenarios where you want distinct pages with
separate URLs, like the above page. This is where the magic of react router doom
package comes into play. Now, this package
helps you simulate multiple page behavior in
a single page application. With react router doom package, you can define routes for different pages within
your application. It's route components
to a specific URL. For instance, you can
set up a route for the about page just like you
would for the home page. Once you start react router Dom, we're going to import a
couple of things for it. First, the browser router, which is a vital part of the react router dump
package and react. It helps your app manage
different QRLs and displays the right components
based on those URLs. Think of it as the
navigator that ensures when users go
to a specific URL, the correct content
appears on this screen. Now let's use the S QR to
change its name to only router. We will use this component to wrap all of our app components. Next, we will import the routes component and the
route component. The routes component will
contain all of our pages, and to switch between
pages using a U at all, we will utilize the
route component. Now this component can
accept a path attribute. For the home page, we will add a forward slash representing
the root route. Then to render the
app component, we will utilize the
component attribute and pass in the name
of the component. We will do the same thing
for the about page. But this time, we want the
path to be slash about. You can remove the
slash if you want. Now, the component
that will be rendered on this path is the
about page component. The header is not included
inside the routes component because we want to render
it on every route. Now inside the browser, navigate to the URO Local hose 3,000 about, and there you go. The About page component is the only one
that was rendered. Now let's add some styling
to the about page. Create an about dot CSS
file, and inside it, you will create a
container class and add these properties to it. This will just make the about text jump to the
center of the page. If we navigate back
to the root route, we will get the tracker up back.
19. Enhancing Navigation: Mastering the NavLink Component in ReactJS: We want to navigate between pages using the header
navigation buttons. However, currently, these
are just pan elements. We need to change them
to hyperlink elements. We will set the H
ref attribute for the home page to the
root route like this. Similarly, we'll do
the same thing for the about link and
set the H ref to a. With these changes, we
can navigate between the a ten home pages
using these buttons. Now, let's focus on highlighting the active navigation link with a different color and style. When we are on the at page, the a navigation link
should be highlighted. But the challenge
here is that we don't want the page to reload. Every time the page reloads, our application will
lose its state, and all the data
would be deleted. To prevent this from happening, the reacro dom package provides a useful
component called Navnk. The noveling component
from react router Dom is like an enhanced navigation
link for react apps. It's similar to the ACML A tag, but instead of using
the H t attribute, we use another one called two. The novelin component
automatically applies styling
for active links. When users click on novel, it visually highlights
the Korean page, creating a smoother more
intuitive navigation experience. Now to achieve this, let's
create a new class in the header dot CSS file for
the headers active state. My find this class already
defined in the file. If you don't find
it, so follow along. Within this class, we'll adjust the color
using this code, representing a blue color. Let's make it slightly darker. Now return to the HodogS x file and inside the first nav link inside the class name attribute, enclose it with curly basis. Pass in in function that accepts an object
containing two properties, is active and is pending. The es active property
will be set to true if the URL path in the
browser matches the URL path inside
the two attribute. The es pending property on the other hand is
used for managing navigation when waiting for
data or ACN operations. Now within this callback, we need to return a class name. We'll conditionally return
the header item class. Along with the header
item active class, if the e active
property is true. Feel free to add more
than one class if needed. If it's not active, let's check the Es
pending property. If true, return the
hydro item class along with the hydro
item pending class. Now let's define the hydro item pending class in
the hydrod SS file. Well let's just de test
color to light blue. Return to the hydro
comoponent here, when the e pending
property is also false, apply the hydro item class. Now let's copy all
of this pasted inside the second
N link component. When testing this
in the browser, the changes may not be
immediately apparent. However, if we zoom in, we'll notice the
dark blue color. Let's just make it more
distinct by changing the color to green and increasing
the font weight to 800. Let's try to add a text decoration property
set to underline. Now if we test these
changes in the browser, it's now more clear
which saving is active and on which page
we are currently located.
20. Mastering the Link Component and Creating a Custom 404 Page: Reapplication with
multiple routes, we have to handle the
scenario where user requests a route that doesn't
exist in our routes list. This means we have to handle
the page not found error. We can easily do that inside
the index DGS file by adding a new route component at the end of the routes list. This time, we will use
the element attribute, which can hold any GSX code, even a component like this. However, we will
only render a div with a message saying
page node found, and add a link to navigate
back to the home page. We don't want to reload the page when we
click on this link. We want our app to work like
a mobile app and be fast. In a mobile app, when you switch between sections or pages, the mobile app doesn't refresh. In react, we can use
the NAV bar component, just like we did in the header. But remember, the NAV bar should only be used
for navigation links. That's why the react
router dom package provides another component
for normal links. This component is named Link. Make sure to import
it at the top. Now you can use the
link component just like you use a normal
hyper link element. Use opening and closing tags, and between them, you can
add text like go back home. For the link at all, use the two attribute like this. Now, the most important part here is the path of this route. It should be set
to a star symbol. This way, when the
URL path changes, react router dom will
check the available routes list and the
order they were defined. I'll start comparing
the first route, which is the root route. If the paths don't match, it will move to the
next one in order. If it reaches a route
with a star symbol path, it will stop and
select that route. This is why I mentioned
that you need to place the route at the
end of the routes list. Otherwise, any
route you put below this general route
will never be reached. All right. Let's
check the browser. As you can see, if the
route path doesn't exist, we will render this message. When we click on this link, we will switch back to the
home page without reloading.
21. Persistent State Management in React: Maintaining Data Across Routes: Adding routes to
our application, we face another challenge. When we add an item to the
list and then navigate to the about page and
return back to home, that item will not be there. This is simply because
the app component gets re rendered every
time the route changes, and when that happens, all these states will return
to their initial values. Here the filtered tasks array will return to an empty array, and all of our
data will be lost. We can fix this by removing the home route from the
routes list and rendering the app component
directly outside the routes component and
inside the router component. This is because inside the
app component will define a home route by wrapping all of the GSX code inside
the routes component. The route component cannot be used outside the
router component. That's why we added the
app component inside the router component in
the index to GS file. I'll take all of this
code and create a route using the route component that
refers to the route path. Then inside the
element attribute, add an opening and
closing tag like so, and paste the code
we cut earlier. If we test this in the browser, you'll notice that
the note found page was rendered
alongside the home page. We will fix that
in just a moment. But now at least when we add an item to the list and
switch between routes, the item will be there. This means the app component
didn't get re rendered. Now that's simply because the
route component will always re render the component
whenever the path changes. What we did here is we
made only the GSX code, the part that gets
re rendered so that all the states
will not be touched. Now, the reason why the not
found page gets rendered on the home page is
because we have to put all of our
routes in one place. The first thing I'm
going to do is to take all of the
home page GSX code. Cut it, and then inside
the components folder. I will create a new page
component and name it home. Let's support react from react. Define the home
function component. And return all the GSX code that we took from
the app component, and don't forget to export the home component
at the bottom. Now we have to pass all of these states and variables from the app component to the
home component as props. Here, open an object and copy all of these
properties into your code. Also make sure to import any other component that
was used into this file. Now inside the app component, we will use the home
component in here. And make sure to
port it at the top. Let's remove ports that
we don't need anymore. Now finally, we have to pass
in all the required props. You can copy and paste
the list of props here and set each prop to
its corresponding variable. After doing that, we have to
remove all the routes from the index DGS file and place them inside
the app component. Remember, we're doing all
of this e to make sure that the routes component
would not re render the entire app component, which would cause it
to lose the app state. Now here, we can actually remove the back slash and just
leave it like that. If we want to set
a specific route as the index of our app, like the home here, we can add the attribute index without setting it to any value, by default, it will
be set to true. Inside the index to GS file, we have to remove
the routes component because in the
entire application, we should have only
one routes component. Let's also remove
any used ports. Right. Now inside the browser, let's add a task item. When we switch between routes, the task item will
not be deleted.
22. Mastering Data Fetching in React: Building an About Page with API Integration: Let's now create a
better about page. Let's remove this and add a depth element with the
class name a container. You will find the CSS file
in the resources section. Now inside here, we will have an H tool element that
says about our services. Behind it a paragraph
element where we can describe what our app is
all about. We can write. We are here to provide you with a simple task tracker
app to help you stay organized and manage
your tasks efficiently. Save this and in the browser, you will see the changes
on the above page. Next below this paragraph, we will have another di
section where we will fetch some programming
jokes from an API. Give this dif the class
name joke section. Inside it, we will have an H three width text that
says programming joke. And below it, a span element where we will render
the joke content. Basically, we will fetch one
joke on every page render. Let's add a U state, and name it joke to
save the joke and set its initial value
to an object with a content property set to null. Now in reac gas to fetch
data from an external IBI, we have to use the
user fat hook. By using it, we can wait for the fetching operation to end. When it ends, we will re render the page with
the fetched data. Let's keep the dependencies
way empty for now. Then inside the use
effect callback, we will define a function
and name it fetch jokes. This function will
be asynchronous because we want to wait for
the fetching operation. Inside it, we'll use a
tri catch block to catch any potential errors
and print them to the console using the
console dot error method. Inside the tri blog, declare a constant
named response and use the await
keyword to stop the execution of the
code until we finish fetching the joke using
the fetch function. This function will accept the AP IURL as the
first argument. Go ahead and copy
the URL as well. This is a free API that returns one joke about programming
on each request. Next, declare a data
constant, and again, use the await keyword and call the JSM method
on the response. Now, this method specifically passes the response body as JSM. JCN is just JavaScript
object notation, converting it into a
Javascript object. When we have the data
as a Javascript object, we can set the joke state and update the content property
with data dot joke. Now, we only still need to call the fetched jokes function at the bottom of the
use effect callback. By keeping the array
of dependencies empty, the use effect hook will run just once after the
component mounts. And by mount, I mean when the component first
renders in the browser. If we save this and
test it in the browser, when we switch routes, the use effect
will be triggered, and we will see the joke there. But there is something
we need to fix. Currently, if you notice, the joke can sometimes
be undefined. So if we add a console
log here and go back to the browser and
switch between routes to execute the
fetching operation, and the console,
we will note that sometimes the joke is undefined, To fix this, we can use an if statement here and check
if the joke is undefined. If it is, we will run the
Ft joke function again. Yes, we can do that
because in JavaScript, calling a function inside
itself is known as recursion. It's a technique for
solving problems by breaking them into
smaller instances using the same function. Add an S statement to handle the case where
we have a joke. In this case, we can
update the joke content. Now, if we test this
from the browser, make sure to clear the console. Then go to home and switch
back to the about page. You'll notice that
we got the joke. But in the console, we can see that we fetch it two jokes, which means that the use effect has been triggered two times, and that's te to
the internal state of the about page component. Let's fix this step by step. First, let's add a new state
and name it is fetching. This state will be
used to make it clear in the browser that
we are fetching data. Set its initial value to
true because we're going to fetch the data directly
when the component mounts. Next, let's come here when the
fetching data has stopped, and before we save the data, let's set the is
fetching state to false and do the same thing when we get an inside the catch block. Now, in the GSX code, we want to inform the user
that we are fetching, so they don't think that our
app is broken or something. So put this span element
inside a pair of curly braces and check
if is fetching is true. Then we return a text saying
fetching with three dots. We can test this in the browser. As you can see, the
fetching message is there, but it disappears very fast. We can slow it down by opening the Dev tools
window and going to the network tab, side here, search for this
menu and change it from not throlling
to slow three G. This will emulate the
experience of browsing the Internet using a slow and limited mobile
network connection, which will slow down
the fetching of the choke from the Joke SapI. This will help us see the fetching messages
in the browser. By doing this, we can discover a new issue in our
apps functionality. In the console,
you can note that the use effect hook is
triggered many times. In each time the
data is undefined, and finally, we get
the data from the API. But even then the use effect gets triggered one more time, resulting in fetching
two jokes from the API. Users may not note this. Our job as developers, is to discover these small
errors and fix them. First, we will add a
fetched property to the joke object state and set
its initial value to true. We will then come here before
the fetch joke function and check if joke dot fetch
is set to true or not. If it is not, then we will
stop the execution of the code with a return statement and we will not fetch the data. But if it is true, then we will fetch the data. And when we finish, we will set the
fetched property to force so that we will not
fetch the data again. This time, since the use effect depends on the value of
the fetched property, it needs to be added inside
the dependencies array. All right. Now in the browser, if we test the about page again, we will notice that the
problem is getting worse. Now we're fetching
the data many times. Even when we have joke data. But don't worry, this
problem can be fixed using a use effect feature called
cleaning up after effects. This is done by returning a callback function at the
end of the use effect hook, where we can clean
up some variables. In our case, we want to set the effect joke
property to force. Now we have to add the joke object to the dependencies
away like so. Score back is executed when
the component is unmounted, or when the dependencies and
the dependency y change. It's commonly used for tasks such as counseling,
subscriptions, removing event listeners,
or in our case, resetting states to
their initial values when the effect is
no longer needed. This prevents memory leaks
or unexpected behavior. Now, if we test this
on the browser, everything will work
normally without any issues. Now, we need to handle
one more thing. Imagine if the joke API is down, which means it will not resolve. So the data will
always be undefined. In that case, this statement
will always be truthful, and we will end up executing the fetch joke function forever. To prevent that from happening, we can declare a let
variable outside the fetch joke function
and name it Fetch count. Set its initial value to zero. Then inside the tri
block at the end, we will increase the fetch count by using the plus plus operator. This javascript is called
the post increment operator. It's used to increment the value of a numeric variable by one. Inside this statement, we will require the fetch count to
be smaller or equal to two. Otherwise, we will not execute the fetch joke function again. All right. Now I want to improve the code
here a little bit. It's always a good
practice to reduce the number of use state
functions in your code. For the ease fetching state, we can remove it from
this component and replace it inside the
joke state as a property. Now we can update everything
in one state function. Side the catch block, if we encounter any errors, we can set the joke
content to no joke, and then we will tell them reload so that they
can fetch the data again and set fetch property to force and do the same thing for the ease fetching property. Down here, don't forget to
update the code and use the joke object in order to access the ease fetching state. Nothing will change
in the browser, but it will keep
things in order, and we can prevent
any weird behavior. Don't forget to reset the network throlling
to not throlling. Let's continue to
the next lesson.
23. Mastering Nested Routes in React.js: Navigating Complex App Structures: Sometimes we might want to add nested routes
to our application. By nested routes,
I mean displaying a specific page inside another
one based on the uro path. Let's consider adding
an instant route within the about page. In this case, we need
to add a closing tag, and then add another route
component inside it. By the way, I prefer using the element tag instead
of the component tag, but feel free to keep it as is. Now, this route component
will be self closing and we set the path
attribute to developers. Essentially, we're adding
a page that will display a list of developers who contributed to building
this application. Now let's set the element
attribute to a ti with the text dvted by
or you know what? We can rename the nested
base to team instead. Inside the element attribute, we render a component
named team. Now, go ahead to the
components folder, create a new file
named team TSX. First, and port
react from react, then define the
function. Then exported. Within this component, we'll
return a list of developers. Before that, copy
the following array that contains some fake names. We'll use this array to render
the list of developers. Now, return a di and add
an H two element inside it with the text developers who worked on the
task tracker app. Below this, add an
ordered list element. Inside it, we'll use
the map function to iterate through its
name and index. We'll return a
list name element, setting the key value to the index argument and placing the name argument
within curly braces. Now, save everything and
inside the ap component, replace this d with
the team component. Now, if we save and navigate to the URO path about slash
team in the browser, the developer's list should
appear at the bottom. However, that doesn't happen. The reason is that
we need to go to the at page component within the dev at the outlet component, which can be imported from
the react router dom package. By doing this, we ensure that the team component
is rendered when the router path is equal
to about slash team. Now the outlet component
acts as a placeholder, displaying content based
on the Korean route. It's like a slot where
route content is inserted. This is especially
useful for creating nested layouts or altering different parts of the
pace based on the route. It keeps your code
organized and makes it easy to switch between different sections
of your application. All right now, put in
your mind that we can add even more nested
routes if desired. For example, let's add a route referring
to the index route, which will be rendered when the router path is equal to a. We're onside the router, which means the index route
refers to the about route. This route will render a link component
saying meet the team, referring to the
above team route. I'm adding this link
as a nested route because I want it to appear
based on the ural path. It's the simplest
way to achieve this. Now, in the browser, if we navigate from home
to the above page, we note the meet the
team link at the bottom. Clicking on it changes the URL path causing
the link to disappear, and the team component
to be rendered. You'll observe that
switching between nested routes trigger
the parent component, which is the at page
to be re rendered.
24. Getting Hands-On with useRef: Supercharging Your React Project: Certain modern web applications. When the client
fetches the page, the input field
will automatically be Fox it so that in our case, user can start adding
task items right away. We can achieve this
very easily inside the task form
component with the use of a new react hook
called use RAF, which is like a name tag
for elements in your code. It helps you refer to a
specific element in the dome, so you can interact with
it using JavaScript. Not just for form inputs. You can use it for any element
you want to keep track of. It's like putting
a sticky note on something so you can
find it easily later. When you call the use raf hook, you'll get an object called a F. We can name it input ref. RF is like a
container that holds a reference to a dom
element or a value. Then inside the input element, we will add a RF
attribute and set it equal to the input
F. In this way, we can access the input element. Think of it as a Java
script element selector. There is a condition
to use this ra. It should only be accessed when the input element gets
rendered in the browser. We have to use it inside a use effect hook and add the dependencies
away and keep it empty, so it will only run one time
when the component mounts. Inside this use of fact hook, we can use the
input ref to access the koan value of the ref
from the Korean property. This Korean property refers
to the input element. In order to focus
inside the input field, which means adding the
text bar inside it, we can call the focus
method like so. We usually set the initial
value of the ref to null, which avoids assuming
an initial state and prevents unintended effects. Now, ensure that you
save all changes. Then refresh the web
page in your browser. Upon doing so, you
will observe that the input field gains
focus automatically. As a result, users can
promptly begin interacting with the application
by inputting content without any
further action required. If you want to have a
look at the input ref, you can console log
it and you will get the HTML input element
in the console. Now, if we only
consolg the input rap, then inside the deep tool, you will get an object with
one property named Coan. By the way, we have
an r here saying that a component is changing an uncontrolled input
to be controlled. He's talking about
a component value going from undefined to defined. This is talking about the input element inside
the task form component. Where we set its value
to the input state. The problem here is that the initial state value
should not be undefined. We can change that
easily by adding an empty string to the use state hook
as an initial value. Now if we refresh the paste, the url will not
be printed again.