Unit II
Unit II
REACT JS: Introduction to React React Router and Single Page Applications React
Forms, Flow Architecture and Introduction to Redux More Redux and Client-Server
Communication, Component structure; props: Passing data to components.
React Introduction
ReactJS is a declarative, efficient, and flexible JavaScript library for building reusable
UI components. It is an open-source, component-based front end library responsible
only for the view layer of the application. It was created by Jordan Walke, who was a
software engineer at Facebook. It was initially developed and maintained by
Facebook and was later used in its products like WhatsApp & Instagram. Facebook
developed ReactJS in 2011 in its newsfeed section, but it was released to the public
in the month of May 2013.
Today, most of the websites are built using MVC (model view controller) architecture.
In MVC architecture, React is the 'V' which stands for view, whereas the architecture
is provided by the Redux or Flux.
A ReactJS application is made up of multiple components, each component
responsible for outputting a small, reusable piece of HTML code. The components
are the heart of all React applications. These Components can be nested with other
components to allow complex applications to be built of simple building blocks.
ReactJS uses virtual DOM based mechanism to fill data in HTML DOM. The virtual
DOM works fast as it only changes individual DOM elements instead of reloading
complete DOM every time.
To create React app, we write React components that correspond to various
elements. We organize these components inside higher level components which
define the application structure. For example, we take a form that consists of many
elements like input fields, labels, or buttons. We can write each element of the form
as React components, and then we combine it into a higher-level component, i.e., the
form component itself. The form components would specify the structure of the form
along with elements inside of it.
React create-react-app
Starting a new React project is very complicated, with so many build tools. It uses
many dependencies, configuration files, and other requirements such as Babel,
Webpack, ESLint before writing a single line of React code. Create React App CLI tool
removes all that complexities and makes React app simple. For this, you need to
install the package using NPM, and then run a few simple commands to get a new
React project.
The create-react-app is an excellent tool for beginners, which allows you to create
and run React project very quickly. It does not take any configuration manually. This
tool is wrapping all of the required dependencies like Webpack, Babel for React
DEPARTMENT OF CA 1|Page
project itself and then you need to focus on writing React code only. This tool sets up
the development environment, provides an excellent developer experience, and
optimizes the app for production.
Requirements
The Create React App is maintained by Facebook and can works on any platform,
for example, macOS, Windows, Linux, etc. To create a React Project using create-
react-app, you need to have installed the following things in your system.
1. Node version >= 8.10
2. NPM version >= 5.6
Let us check the current version of Node and NPM in the system.
Run the following command to check the Node version in the command prompt.
1. $ node -v
Run the following command to check the NPM version in the command prompt.
1. $ npm -v
Installation
Here, we are going to learn how we can install React using CRA tool. For this, we
need to follow the steps as given below.
Install React
We can install React using npm package manager by using the following command.
There is no need to worry about the complexity of React installation. The create-
react-app npm package manager will manage everything, which needed for React
project.
1. C:\Users\javatpoint> npm install -g create-react-app
Create a new React project
Once the React installation is successful, we can create a new React project using
create-react-app command. Here, I choose "reactproject" name for my project.
1. C:\Users\javatpoint> create-react-app reactproject
DEPARTMENT OF CA 2|Page
NOTE: We can combine the above two steps in a single command using npx. The
npx is a package runner tool which comes with npm 5.2 and above version.
1. C:\Users\javatpoint> npx create-react-app reactproject
The above command will take some time to install the React and create a new
project with the name "reactproject." Now, we can see the terminal as like below.
The above screen tells that the React project is created successfully on our system.
Now, we need to start the server so that we can access the application on the
browser. Type the following command in the terminal window.
1. $ cd Desktop
2. $ npm start
NPM is a package manager which starts the server and access the application at
default server [Link] Now, we will get the following screen.
DEPARTMENT OF CA 3|Page
Next, open the project on Code editor. Here, I am using Visual Studio Code. Our
project's default structure looks like as below image.
In React application, there are several files and folders in the root directory. Some of
them are as follows:
1. node_modules: It contains the React library and any other third party libraries
needed.
2. public: It holds the public assets of the application. It contains the [Link] where
React will mount the application by default on the <div id="root"></div> element.
3. src: It contains the [Link], [Link], [Link], [Link], [Link], and [Link]
files. Here, the [Link] file always responsible for displaying the output screen in React.
4. [Link]: It is generated automatically for any operations where npm
package modifies either the node_modules tree or [Link]. It cannot be
published. It will be ignored if it finds any other place rather than the top-level
package.
DEPARTMENT OF CA 4|Page
5. [Link]: It holds various metadata required for the project. It gives information
to npm, which allows to identify the project as well as handle the project?s
dependencies.
6. [Link]: It provides the documentation to read about React topics.
React Environment Setup
Now, open the src >> [Link] file and make changes which you want to display on
the screen. After making desired changes, save the file. As soon as we save the file,
Webpack recompiles the code, and the page will refresh automatically, and changes
are reflected on the browser screen. Now, we can create as many components as we
want, import the newly created component inside the [Link] file and that file will be
included in our main [Link] file after compiling by Webpack.
Next, if we want to make the project for the production mode, type the following
command. This command will generate the production build, which is best
optimized.
$ npm build
React Features
Currently, ReactJS gaining quick popularity as the best JavaScript framework among
web developers. It is playing an essential role in the front-end ecosystem. The
important features of ReactJS are as following.
o JSX
o Components
o One-way Data Binding
o Virtual DOM
o Simplicity
o Performance
JSX
JSX stands for JavaScript XML. It is a JavaScript syntax extension. Its an XML or HTML
like syntax used by ReactJS. This syntax is processed into JavaScript calls of React
Framework. It extends the ES6 so that HTML like text can co-exist with JavaScript
react code. It is not necessary to use JSX, but it is recommended to use in ReactJS.
Components
ReactJS is all about components. ReactJS application is made up of multiple
components, and each component has its own logic and controls. These components
can be reusable which help you to maintain the code when working on larger scale
projects.
One-way Data Binding
ReactJS is designed in such a manner that follows unidirectional data flow or one-
way data binding. The benefits of one-way data binding give you better control
throughout the application. If the data flow is in another direction, then it requires
additional features. It is because components are supposed to be immutable and the
data within them cannot be changed. Flux is a pattern that helps to keep your data
DEPARTMENT OF CA 5|Page
unidirectional. This makes the application more flexible that leads to increase
efficiency.
Virtual DOM
A virtual DOM object is a representation of the original DOM object. It works like a
one-way data binding. Whenever any modifications happen in the web application,
the entire UI is re-rendered in virtual DOM representation. Then it checks the
difference between the previous DOM representation and new DOM. Once it has
done, the real DOM will update only the things that have actually changed. This
makes the application faster, and there is no wastage of memory.
Simplicity
ReactJS uses JSX file which makes the application simple and to code as well as
understand. We know that ReactJS is a component-based approach which makes the
code reusable as your need. This makes it simple to use and learn.
Performance
ReactJS is known to be a great performer. This feature makes it much better than
other frameworks out there today. The reason behind this is that it manages a virtual
DOM. The DOM is a cross-platform and programming API which deals with HTML,
XML or XHTML. The DOM exists entirely in memory. Due to this, when we create a
component, we did not write directly to the DOM. Instead, we are writing virtual
components that will turn into the DOM leading to smoother and faster
performance.
React JSX
As we have already seen that, all of the React components have a render function.
The render function specifies the HTML output of a React component. JSX(JavaScript
Extension), is a React extension which allows writing JavaScript code that looks like
HTML. In other words, JSX is an HTML-like syntax used by React that extends
ECMAScript so that HTML-like syntax can co-exist with JavaScript/React code. The
syntax is used by preprocessors (i.e., transpilers like babel) to transform HTML-like
syntax into standard JavaScript objects that a JavaScript engine will parse.
JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures)
in the same file where you write JavaScript code, then preprocessor will transform
these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a
tag name, attributes, and children.
Example
Here, we will write JSX syntax in JSX file and see the corresponding JavaScript code
which transforms by preprocessor(babel).
JSX File
<div>Hello JavaTpoint</div>
Corresponding Output
1. [Link]("div", null, "Hello JavaTpoint");
The above line creates a react element and passing three arguments inside where
the first is the name of the element which is div, second is the attributes passed in
DEPARTMENT OF CA 6|Page
the div tag, and last is the content you pass which is the "Hello JavaTpoint."
Why use JSX?
o It is faster than regular JavaScript because it performs optimization while
translating the code to JavaScript.
o Instead of separating technologies by putting markup and logic in separate
files, React uses components that contain both. We will learn components in a
further section.
o It is type-safe, and most of the errors can be found at compilation time.
o It makes easier to create templates.
React Components
Earlier, the developers write more than thousands of lines of code for developing a single
page application. These applications follow the traditional DOM structure, and making
changes in them was a very challenging task. If any mistake found, it manually searches the
entire application and update accordingly. The component-based approach was introduced to
overcome an issue. In this approach, the entire application is divided into a small logical
group of code, which is known as components.
A Component is considered as the core building blocks of a React application. It makes the
task of building UIs much easier. Each component exists in the same space, but they work
independently from one another and merge all in a parent component, which will be the final
UI of your application.
Every React component have their own structure, methods as well as APIs. They can be
reusable as per your need. For better understanding, consider the entire UI as a tree. Here, the
root is the starting component, and each of the other pieces becomes branches, which are
further divided into sub-branches.
DEPARTMENT OF CA 7|Page
and returns what should be rendered. A valid functional component can be shown in the
below example.
function WelcomeMessage(props) {
return <h1>Welcome to the , {[Link]}</h1>;
}
The functional component is also known as a stateless component because they do not hold
or manage state. It can be explained in the below example.
Example
import React, { Component } from 'react';
class App extends [Link] {
render() {
return (
<div>
<First/>
<Second/>
</div>
);
}
}
class First extends [Link] {
render() {
return (
<div>
<h1>JavaTpoint</h1>
</div>
);
}
}
class Second extends [Link] {
render() {
return (
<div>
<h2>[Link]</h2>
<p>This websites contains the great CS tutorial.</p>
</div>
);
}
}
export default App;
Output:
DEPARTMENT OF CA 8|Page
Class Components
Class components are more complex than functional components. It requires you to extend
from React. Component and create a render function which returns a React element. You can
pass data from one class to other class components. You can create a class by defining a class
that extends Component and has a render function. Valid class component is shown in the
below example.
class MyComponent extends [Link] {
render() {
return (
<div>This is main component.</div>
);
}
}
The class component is also known as a stateful component because they can hold or manage
local state. It can be explained in the below example.
Example
In this example, we are creating the list of unordered elements, where we will dynamically
insert StudentName for every object from the data array. Here, we are using ES6 arrow
syntax (=>) which looks much cleaner than the old JavaScript syntax. It helps us to create our
elements with fewer lines of code. It is especially useful when we need to create a list with a
lot of items.
DEPARTMENT OF CA 9|Page
]
}
}
render() {
return (
<div>
<StudentName/>
<ul>
{[Link]((item) => <List data = {item} />)}
</ul>
</div>
);
}
}
class StudentName extends [Link] {
render() {
return (
<div>
<h1>Student Name Detail</h1>
</div>
);
}
}
class List extends [Link] {
render() {
return (
<ul>
<li>{[Link]}</li>
</ul>
);
}
}
export default App;
Output:
React State
The state is an updatable structure that is used to contain data or information about
the component. The state in a component can change over time. The change in state
over time can happen as a response to user action or system event. A component
with the state is known as stateful components. It is the heart of the react
component which determines the behavior of the component and how it will render.
They are also responsible for making a component dynamic and interactive.
A state must be kept as simple as possible. It can be set by using
the setState() method and calling setState() method triggers UI updates. A state
DEPARTMENT OF CA 10 | P a g e
represents the component's local state or information. It can only be accessed or
modified inside the component or by the component directly. To set an initial state
before any interaction occurs, we need to use the getInitialState() method.
For example, if we have five components that need data or information from the
state, then we need to create one container component that will keep the state for all
of them.
Defining State
To define a state, you have to first declare a default set of values for defining the
component's initial state. To do this, add a class constructor which assigns an initial
state using [Link]. The '[Link]' property can be rendered
inside render() method.
Example
The below sample code shows how we can create a stateful component using ES6
syntax.
import React, { Component } from 'react';
class App extends [Link] {
constructor() {
super();
[Link] = { displayBio: true };
}
render() {
const bio = [Link] ? (
<div>
<p><h3>Javatpoint is one of the best Java training institute in Noida,
Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java
developers and trainers from multinational companies to teach our campus stude
nts.</h3></p>
</div>
) : null;
return (
<div>
<h1> Welcome to JavaTpoint!! </h1>
{ bio }
</div>
);
}
}
export default App;
To set the state, it is required to call the super() method in the constructor. It is
because [Link] is uninitialized before the super() method has been called.
Output
DEPARTMENT OF CA 11| P a g e
Changing the State
We can change the component state by using the setState() method and passing a
new state object as the argument. Now, create a new method toggleDisplayBio() in
the above example and bind this keyword to the toggleDisplayBio() method
otherwise we can't access this inside toggleDisplayBio() method.
[Link] = [Link](this);
Example
In this example, we are going to add a button to the render() method. Clicking on
this button triggers the toggleDisplayBio() method which displays the desired output.
import React, { Component } from 'react';
class App extends [Link] {
constructor() {
super();
[Link] = { displayBio: false };
[Link]('Component this', this);
[Link] = [Link](this);
}
toggleDisplayBio(){
[Link]({displayBio: ![Link]});
}
render() {
return (
<div>
<h1>Welcome to JavaTpoint!!</h1>
{
[Link] ? (
<div>
<p><h4>Javatpoint is one of the best Java training institute in
Noida, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experience
d Java developers and trainers from multinational companies to teach our campu
s students.</h4></p>
<button onClick={[Link]}> Show Less </button
>
</div>
):(
<div>
<button onClick={[Link]}> Read More </but
ton>
DEPARTMENT OF CA 12 | P a g e
</div>
)
}
</div>
)
}
}
export default App;
Output:
When you click the Read More button, you will get the below output, and when you
click the Show Less button, you will get the output as shown in the above image.
React Props
Props stand for "Properties." They are read-only components. It is an object which
stores the value of attributes of a tag and work similar to the HTML attributes. It
gives a way to pass data from one component to other components. It is similar to
function arguments. Props are passed to the component in the same way as
arguments passed in a function.
Props are immutable so we cannot modify the props from inside the component.
Inside the components, we can add attributes called props. These attributes are
available in the component as [Link] and can be used to render dynamic data in
our render method.
When you need immutable data in the component, you have to add props
to [Link]() method in the [Link] file of your ReactJS project and used it
inside the component in which you need. It can be explained in the below example.
Example
[Link]
import React, { Component } from 'react';
class App extends [Link] {
render() {
return (
<div>
<h1> Welcome to { [Link] } </h1>
<p> <h4> Javatpoint is one of the best Java training institute in Noida, De
lhi, Gurugram, Ghaziabad and Faridabad. </h4> </p>
DEPARTMENT OF CA 13 | P a g e
</div>
);
}
}
export default App;
[Link]
import React from 'react';
import ReactDOM from 'react-dom';
import App from './[Link]';
Default Props
It is not necessary to always add props in the [Link]() element. You can
also set default props directly on the component constructor. It can be explained in
the below example.
Example
[Link]
import React, { Component } from 'react';
class App extends [Link] {
render() {
return (
<div>
<h1>Default Props Example</h1>
<h3>Welcome to {[Link]}</h3>
<p>Javatpoint is one of the best Java training institute in Noida, Delhi, Gu
rugram, Ghaziabad and Faridabad.</p>
</div>
);
}
}
[Link] = {
name: "JavaTpoint"
}
export default App;
[Link]
import React from 'react';
DEPARTMENT OF CA 14 | P a g e
import ReactDOM from 'react-dom';
import App from './[Link]';
[Link](<App/>, [Link]('app'));
Output
DEPARTMENT OF CA 15 | P a g e
}
export default App;
[Link]
import React from 'react';
import ReactDOM from 'react-dom';
import App from './[Link]';
[Link](<App/>, [Link]('app'));
Output:
React Forms
Forms are an integral part of any modern web application. It allows the users to
interact with the application as well as gather information from the users. Forms can
perform many tasks that depend on the nature of your business requirements and
logic such as authentication of the user, adding user, searching, filtering, booking,
ordering, etc. A form can contain text fields, buttons, checkbox, radio button, etc.
Creating Form
React offers a stateful, reactive approach to build a form. The component rather than
the DOM usually handles the React form. In React, the form is usually implemented
by using controlled components.
There are mainly two types of form input in React.
1. Uncontrolled component
2. Controlled component
Uncontrolled component
The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself
handles the form data. Here, the HTML elements maintain their own state that will be
updated when the input value changes. To write an uncontrolled component, you
need to use a ref to get form values from the DOM. In other words, there is no need
to write an event handler for every state update. You can use a ref to access the input
field value of the form from the DOM.4K
OOPs Concepts in Java
Example
In this example, the code accepts a field username and company name in an
uncontrolled component.
import React, { Component } from 'react';
class App extends [Link] {
constructor(props) {
super(props);
DEPARTMENT OF CA 16 | P a g e
[Link] = [Link](this);
[Link] = [Link]();
}
updateSubmit(event) {
alert('You have entered the UserName and CompanyName successfully.');
[Link]();
}
render() {
return (
<form onSubmit={[Link]}>
<h1>Uncontrolled Form Example</h1>
<label>Name:
<input type="text" ref={[Link]} />
</label>
<label>
CompanyName:
<input type="text" ref={[Link]} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Output
When you execute the above code, you will see the following screen.
After filling the data in the field, you get the message that can be seen in the below
screen.
Controlled Component
In HTML, form elements typically maintain their own state and update it according to
the user input. In the controlled component, the input form element is handled by
the component rather than the DOM. Here, the mutable state is kept in the state
property and will be updated only with setState() method.
Controlled components have functions that govern the data passing into them on
every onChange event, rather than grabbing the data only once, e.g., when you click
DEPARTMENT OF CA 17 | P a g e
a submit button. This data is then saved to state and updated with setState()
method. This makes component have better control over the form elements and
data.
A controlled component takes its current value through props and notifies the
changes through callbacks like an onChange event. A parent component "controls"
this changes by handling the callback and managing its own state and then passing
the new values as props to the controlled component. It is also called as a "dumb
component."
Example
import React, { Component } from 'react';
class App extends [Link] {
constructor(props) {
super(props);
[Link] = {value: ''};
[Link] = [Link](this);
[Link] = [Link](this);
}
handleChange(event) {
[Link]({value: [Link]});
}
handleSubmit(event) {
alert('You have submitted the input successfully: ' + [Link]);
[Link]();
}
render() {
return (
<form onSubmit={[Link]}>
<h1>Controlled Form Example</h1>
<label>
Name:
<input type="text" value={[Link]} onChange={[Link]
nge} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Output
When you execute the above code, you will see the following screen.
DEPARTMENT OF CA 18 | P a g e
After filling the data in the field, you get the message that can be seen in the below
screen.
DEPARTMENT OF CA 19 | P a g e
checked={[Link]}
onChange={[Link]} />
</label>
<br />
<label>
Number of persons:
<input
name="numberOfPersons"
type="number"
value={[Link]}
onChange={[Link]} />
</label>
</form>
);
}
}
export default App;
Output
The Example
Before we go further, take a look at the following example:
What you have here is a simple React app that uses React Router to provide
all of the navigation and view-loading goodness! Click on the various links to
load the relevant content, and feel free to open up this page in its own browser
window to use the back and forward buttons to see them working.
Getting Started
The first thing we need to do is get our project setup. We'll use our
trusty create-react-app command to do this. From your favorite
terminal, navigate to the folder you want to create your app, and
type the following:
DEPARTMENT OF CA 20 | P a g e
create-react-app react_spa
This will create our new project inside a folder called react_spa. Go
ahead and navigate into this folder:
cd react_spa
Normally, this is where we start messing around with deleting the
existing content to start from a blank slate. We will do that, but first,
we are going to install React Router. To do that, run the following
command:
Now that you've done this, it is time to clean up our project to start
from a clean slate. From inside your react_spa folder, delete
everything found inside your public and src folders. Once you've
done this, let's create our [Link] file that will serve as our app's
starting point. In your public folder, create a file
called [Link] and add the following contents into it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>React Router Example</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
[Link](
<Main/>,
[Link]("root")
DEPARTMENT OF CA 21 | P a g e
);
Our [Link] call lives here, and what we are rendering is
our Main component...which doesn't exist yet. The Main component
will be the starting point for our SPA expedition using React Router,
and we'll see how starting with the next section.
</div>
</div>
);
}
DEPARTMENT OF CA 22 | P a g e
}
I know that this doesn't look all fancy and styled, but that's OK for
now. We will deal with that later. The important thing to call out is
that there is nothing React Router specific here. ABSOLUTELY
NOTHING!
Creating our Content Pages
Our app will have three pages of content. This content will just be a
simple component that prints out some JSX. Let's just get those
created and out of the way! First, create a file called [Link] in
our src directory and add the following content:
DEPARTMENT OF CA 23| P a g e
convallis erat elementum. Ut aliquam, ipsum vitae
gravida suscipit, metus dui bibendum est, eget rhoncus nibh
metus nec massa. Maecenas hendrerit laoreet augue
nec molestie. Cum sociis natoque penatibus et magnis
dis parturient montes, nascetur ridiculus mus.</p>
Next, create a file called [Link] in the same location and add in the
following:
DEPARTMENT OF CA 24 | P a g e
<p>The easiest thing to do is post on
our <a href="[Link]
</p>
</div>
);
}
}
That's the last of our content we are going to add. If you took a look
at what it is you were adding, you'll see that these components can't
get any simpler. They just returned some boilerplate JSX content.
Now, make sure to save all of your changes to these three files.
We'll look at how to make them useful shortly.
DEPARTMENT OF CA 25 | P a g e
The first thing we are going to do is define our routing region.
Inside our Main component's render method, add the following
highlighted lines:
</div>
</div>
</HashRouter>
);
}
}
The HashRouter component provides the foundation for the
navigation and browser history handling that routing is
made up of. What we are going to do next is define our
navigation links. We already have list elements with
the a element defined. We need to replace them with the
more specialized NavLink component, so go ahead and
make the following highlighted changes:
class Main extends Component {
render() {
return (
<HashRouter>
<div>
<h1>Simple SPA</h1>
<ul className="header">
<li><NavLink to="/">Home</NavLink></li>
<li><NavLink to="/stuff">Stuff</NavLink></li>
<li><NavLink to="/contact">Contact</NavLink></li>
</ul>
<div className="content">
</div>
</div>
</HashRouter>
);
}
DEPARTMENT OF CA 26 | P a g e
}
For each link, pay attention to the URL we are telling our
router to navigate to. This URL value (defined by
the to prop) acts as an identifier to ensure the right content
gets loaded. The way we match the URL with the content
is by using a Route component. Go ahead and add the
following highlighted lines:
class Main extends Component {
render() {
return (
<HashRouter>
<div>
<h1>Simple SPA</h1>
<ul className="header">
<li><NavLink to="/">Home</NavLink></li>
<li><NavLink to="/stuff">Stuff</NavLink></li>
<li><NavLink to="/contact">Contact</NavLink></li>
</ul>
<div className="content">
<Route path="/" component={Home}/>
<Route path="/stuff" component={Stuff}/>
<Route path="/contact" component={Contact}/>
</div>
</div>
</HashRouter>
);
}
}
As you can see, the Route component contains a path prop. The
value you specify for the path determines when this route is going to
be active. When a route is active, the component specified by
the component prop gets rendered. For example, when we click on
the Stuff link (whose path is /stuff as set by
the NavLink component's to prop), the route whose path value is
also /stuff becomes active. This means the contents of
our Stuff component get rendered.
You can see all of this for yourself. Jump back to your browser to
see the live updates or run npm start again. Click around on the links
to see the content loading in and out. Something seems off, though,
right? The content for our home page seems to always display even
if we are clicking on the Stuff or Contact links:
DEPARTMENT OF CA 27 | P a g e
That seems problematic. We'll look at how to fix that and do many
more little housekeeping tasks in the next section when we go one
level deeper into using React Router.
It's the Little Things
In the previous section, we got our SPA mostly up and running. We
just wrapped our entire routing region inside a HashRouter component,
and we separated our links and the place our links would load by
using the NavLink and Route components respectively. Getting our
example mostly up and running and fully up and running are two
different things. In the following sections, we'll close those
differences.
Fixing our Routing
We ended the previous section by calling out that our
routing has a bug in it. The contents of
our Home component is always displaying. The reason for it
is because the path for loading our Home component is /.
Our Stuff and Contact components have the / character as
part of their paths as well. This means
our Home component always matches whatever path we
are trying to navigate to. The fix for that is simple. In
DEPARTMENT OF CA 28 | P a g e
the Route component representing our home content, add
the exact prop as highlighted below:
<div className="content">
<Route exact path="/" component={Home}/>
<Route path="/stuff" component={Stuff}/>
<Route path="/contact" component={Contact}/>
</div>
This prop ensures the Route is active only if the path is an
exact match for what is being loaded. If you preview your
app now, you'll see that the content loads correctly with
the home content only displaying when our app is in the
home view.
Adding Some CSS
Right now, our app is completely unstyled. The fix for that
is easy. In your src folder, create a file
called [Link] and add the following style rules into it:
body {
background-color: #FFCC00;
padding: 20px;
margin: 0;
}
h1, h2, p, ul, li {
font-family: sans-serif;
}
[Link] li {
display: inline;
list-style-type: none;
margin: 0;
}
[Link] {
background-color: #111;
padding: 0;
}
[Link] li a {
color: #FFF;
font-weight: bold;
text-decoration: none;
padding: 20px;
display: inline-block;
}
.content {
background-color: #FFF;
padding: 20px;
}
.content h2 {
padding: 0;
margin: 0;
}
DEPARTMENT OF CA 29 | P a g e
.content li {
margin-bottom: 10px;
}
After you've done this, we need to reference this style
sheet in our app. At the top of [Link], add
the import statement to do just that:
import React from "react";
import ReactDOM from "react-dom";
import Main from "./Main";
import "./[Link]";
[Link](
<Main/>,
[Link]("root")
);
Save all of your changes if you haven't done so yet. If you preview
the app now, you'll notice that it is starting to look a bit more like the
example we started out with:
We are almost done here! There is just a few more things we need
to do.
Highlighting the Active Link
Right now, it's hard to tell which link corresponds to content that is
currently loaded. It would be useful to have some sort of a visual cue
to solve this. The creators of React Router have already thought of
that! When you click on a link, a class value of active is automatically
assigned to it.
For example, this is what the HTML for clicking on the
Stuff link looks like:
<a aria-current="true" href="#/stuff" class="active">Stuff</a>
DEPARTMENT OF CA 30 | P a g e
This means all we really have to do is add the appropriate CSS that
lights up when an element has a class value of active set on it. To
make this happen, go back to [Link] and add the following style
rule towards the bottom of your document:
.active {
background-color: #0099FF;
}
Once you have added this rule and saved your document, go back
to your browser and click around on the links in our example. You'll
see that the active link whose content is displayed from is
highlighted with a blue color. What you will also see is our Home link
always highlighted. That isn't correct. The fix for that is simple. Just
add the exact prop to our NavLink component representing our home
content:
<li><NavLink exact to="/">Home</NavLink></li>
<li><NavLink to="/stuff">Stuff</NavLink></li>
<li><NavLink to="/contact">Contact</NavLink></li>
Once you have done that, go back to our browser. You'll
see that our Home link only gets the active color treatment
when the home content is displayed:
DEPARTMENT OF CA 31 | P a g e
DEPARTMENT OF CA 32 | P a g e