0% found this document useful (0 votes)
0 views

Module5

Routing is a fundamental concept in web development that allows browsers to request and display web pages using unique URLs, evolving from traditional page loads to dynamic content updates with AJAX in Web 2.0. In React, routing is managed using React Router, which provides components like BrowserRouter and Route to facilitate navigation and rendering of components based on the current URL. The document also discusses various linking methods and the use of hooks like useEffect to manage component lifecycle and side effects.

Uploaded by

Rohan K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Module5

Routing is a fundamental concept in web development that allows browsers to request and display web pages using unique URLs, evolving from traditional page loads to dynamic content updates with AJAX in Web 2.0. In React, routing is managed using React Router, which provides components like BrowserRouter and Route to facilitate navigation and rendering of components based on the current URL. The document also discusses various linking methods and the use of hooks like useEffect to manage component lifecycle and side effects.

Uploaded by

Rohan K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Routing

WHAT IS ROUTING?

 The most basic concept behind the web (what we call Web 1.0) is that a
web browser requests a web page from a web (HTTP) server using a
unique URL.
 The web server then responds with an HTML page that is rendered in
the browser, as shown in Figure 12-1.
 When a user clicks a link on a web page, it requests a new HTML page,
which the browser downloads and displays instead of the current page.
 Browsers and servers maintain a user’s state between different web
pages by using browser cookies, the localStorage API, and server-side
data.

The problem with loading a new web page each time a user clicks a link is that
it doesn’t create a smooth experience for the user, and it doesn’t allow for
refreshing data dynamically.
The whole web page is downloaded and rendered each time a new URL is
loaded.
AJAX (which stands for Asynchronous JavaScript and XML) was created to
solve this problem.
With AJAX, JavaScript dynamically loads data into a web page without loading
a new HTML page.
AJAX made dynamic web user interfaces possible, and JavaScript libraries and
frameworks made building them easier. This is what was referred to as Web
2.0.
Now instead of the web browser requesting new pages from a web server, the
browser only loads the first page containing the JavaScript code and the
JavaScript virtual machine takes over from there and dynamically loads data
and updates the browser using the DOM API.
JavaScript user interface libraries hijack the original request/response model
that the web was built on.
This works well, but it means that the browser is always displaying the same
HTML page. This is what we call a single page application (SPA).
Having a website or web application that only con- sists of one web page
makes it impossible for other sites to link to specific data within your app or
site using a URL, and it makes it more difficult for search engines to index the
data on your site or in your app.
The solution is to have the JavaScript that runs your web application simulate
the browser’s built-in ability to load web pages that correspond to unique
URLs.

HOW ROUTING WORKS IN REACT


In React, routing has two purposes:
1. To change the window.location property of the browser (when used with a
web browser).
2. To detect the current location and use it to show or hide different
components or combinations of components.
The browser’s window.location.href property is what indicates the current URL
of the web page.
By setting window.location.href without making a server request, a JavaScript
routing program can simulate the native way that browsers change the
rendered view.
What this means is that a user or search engine can navigate to or link to a
specific URL, such as www.example.com/aboutUs.
Once the value of window.location.href changes, this property can be read
using JavaScript and different URLs can be associated with different
components. This association is called a route.

In this example, the Link component changes the current browser location. The
Route components render the correct child component depending on the
browser’s location.
When the browser’s location (after the domain name) is /worn, the
MoreTraveledPath component will be displayed, and when the location is
/untrodden, the LessTraveledPath component will be displayed.

USING REACT ROUTER

React Router can be used for routing in web applications or in mobile apps.
Because of the funda- mental differences in routing in a browser versus routing
in a native mobile app, there are two different versions of React Router:
➤ react-router-dom is the version of React Router for the web.
➤ react-router-native is the version of React Router for native apps.

The Router Component


A router component is the top-level component that makes routing possible. It
handles the changing of the window.location property and it provides React
Router props to components below it.
Selecting a Router React Router contains five different router components:
➤ BrowserRouter
➤ HashRouter
➤ MemoryRouter
➤ StaticRouter
➤ NativeRouter
No matter which router you choose, it’s a convention to import the router
component using the name Router, like this:

 BrowserRouter
BrowserRouter is the Router component that you’ll use most, if not all, of the
time. It uses the HTML5 history API to change the browser’s
window.location.href property. Using BrowserRouter allows your React UI to
simulate the familiar way of navigating the web using URL paths.
 HashRouter
HashRouter uses the part of the URL after the hash symbol (#) to synchronize
the location and the displayed components.
HashRouter relies on the fact that anything after a # in a URL won’t cause a
browser to load a new page by default.
For example, the following two addresses both use the same HTML page:
https://www.example.com/ https://www.example.com/#/aboutUs
The second URL passes a path after a #, which can be read using JavaScript and
used to change the displayed components.
 MemoryRouter
MemoryRouter doesn’t update or read the browser’s window.location
property at all.
Instead, it keeps the routing history in memory. MemoryRouter is useful for
non-browser environments such as React Native, and for in-memory tests of
your user interface.
 StaticRouter
StaticRouter creates a router that never changes. It’s useful for server-side
rendering of React, where the web server passes a path to React on the server
and React generates static code to serve to the user.
 NativeRouter
NativeRouter is used for creating navigation in iOS and Android apps built using
React Native. Keep in mind that React apps can be rendered to many different
types of user interface devices.Native apps handle routing differently from web
browsers, and the NativeRouter component translates the lower-level React
Router components to routing commands that work with your target mobile
operating system
Linking to Routes
React Router has three different linking components:
➤ Link
➤ NavLink
➤ Redirect
The first two linking components are essentially wrappers around the HTML a
element with some additional features and capabilities added. The Redirect
component changes the current URL with- out user interaction.
 Internal Linking with Link
Because React Router overrides the default behaviour of links in a browser,
you can’t simply link between routes using the a element as you normally
would in a website
The Link element is the basic linking element in React Router. All it requires is a
path to link to, which can be provided using the to attribute, and a single child
node, as in the following example:

The value of the to attribute can be a string (or an expression that evaluates to
a string) or an object. If the to property is specified as an object, the properties
of the object are concatenated to create the destination location.

 Linking with a String


If you pass a string to the to attribute, it can be any valid internal path that you
would normally use as the value of the href attribute with the HTML a element.
Any path that you pass to the Link component will be used to update the
browser location relative to the path of the app. Because using Link updates
the URL relative to the app, the following example won’t work as you might
expect:

 Linking with an Object


To use an object as the value of the to attribute, specify a combination of the
allowed properties:
➤ pathname: A string containing the path to link to.
➤ search: A string containing query parameters (the question mark followed
by the name=value pairs that form an HTML querystring).
➤ hash: A string containing the hash symbol (#) followed by any values you
want to provide to the destination route in the hash portion of the URL.
➤ state: An object containing state that you want to persist in the destination
location.

Additional Link Props


The Link component can receive several optional props. These include replace,
component, and pass-through props, which are discussed next.
replace
Normally, when a Link element is clicked, React Router adds a new location
entry to the browser history stack. If you want to return to the route you were
previously at, you can use the browser back button or change the browser’s
position in the history stack. The replace attribute replaces the current entry in
the history stack rather than adding a new one:

component
The component attribute takes a custom navigation component as its value.
You can use the component attribute to supply the name of the component
you’d like to use in place of the default Link component. To create a custom
navigation component that you want to use for the link and pass the prop from
the Link component through to it, do this:

 Internal Navigation with NavLink


Navigation links are a subset of internal links within an app. They’re used for
changing modes, tabs, or pages within a web application. Examples of
navigation links include the links in a navigation bar or mobile site navigation
menu. Navigation links function the same as any other link in a web
application, but it’s good user interface design to indicate which link is
currently active,
React Router’s NavLink component creates navigation links. The difference
between a NavLink and a Link component is that the NavLink has attributes
that allow it to be styled when the value of its to attribute matches the
browser’s current location. You can style a NavLink component using either the
activeClassName attribute, which accepts a CSS class name, or the activeStyle
attribute, which accepts a style object:

 Automatic Linking with Redirect


The Redirect component changes the current URL by replacing the current
location in the history stack when it renders. Like the Link and NavLink
components, Redirect takes an attribute named to, which can have a value of a
string or object. Unlike Link and NavLink, a Redirect doesn’t have children.
Redirect is often used to change the URL in response to the result of a
conditional statement, as in the following example

Creating Routes
The Route component is the one that actually creates routes. In its simplest
form, Route takes an attribute named path, which it compares with the current
location. If there’s a match, Route will render its children:

Restricting Path Matching You can use the exact attribute with Route to restrict
path matching to exact matches
If you want to enforce the ending slash in path matching, use the strict
attribute:
 Using URL Parameters
URLs frequently contain dynamic data that need to be available inside of child
components. For example, in the following path, the directory name user is
followed by a slash and then a number:

This type of URL usually indicates that the number represents a unique
identifier for a user, rather than a component named “5455” (which isn’t a
valid component name)
The component Prop
Instead of specifying the component to be rendered by a matching route using
children of the Route component, you can use the component attribute

React Router will use the component passed to the component attribute to
create and render a new React element. Using the component attribute results
in the component being unmounted and rendered with every render.
 Render Props
Another option for rendering components when routes match is to specify a
function inside the render attribute. When the route matches, this function will
be called.
Using the render attribute doesn’t require React Router to create an element,
so it avoids the unmounting and mounting on each render that using the
component attribute does.
Use of Route’s render attribute is an example of an advanced technique in
React known as render props. A render prop is a function provided to a
component using props that the component calls instead of using its own
render method.
 Switching Routes
The Switch component causes only the first matching Route to be rendered.
This is useful in cases where you don’t want to render multiple routes when
there are multiple matches. To use Switch, wrap the routes that you want it to
choose the first match from with a element

 Rendering a Default Route


Switch can also be used to render a default route when no other routes match.
The default route should be the last one, and a Route with no path can be used
so that it matches any location
Behind the Scenes: location, history, and match

The history Object


The history object refers to the history package, which is separate from React
Router, but which React Router depends upon. The history object’s job is to
keep a record of the locations navigated to in the current session and to make
changing the location possible.
The concept of session history is device-independent, but is implemented in
several different ways for different environments (which correspond to the
router components in React Router):
➤ Browser history.
➤ Hash history.
➤ Memory history.
You can gain access to the history object in your React code by using the
useHistory hook or by using the withRouter higher-order function.
The location Object
A location object contains information about where the app is or has been or
will be. It can contain a pathname, a querystring, a hash, state data, and a key.
Location objects are stored in the history stack and can be accessed in a Route
component or by using the withRouter higher-order function.
 The match Object
The match object contains information about how a Route’s path matches the
URL. Just as with the location and history objects, you can access the match
object in several different ways:
➤ Inside a Route component.
➤ By using the withRouter higher-order component.
➤ By using a hook.The match object contains the following properties:

➤ params: An object containing the key/value pairs passed from the URL,
which correspond to dynamic parts of the URL. For example, if the route’s path
is /user/:id, id will be in the params property.
➤ isExact: A Boolean that’s true if the entire URL matches, with no characters
after it.
➤ path: The pattern that was used to make the match.
➤ url: The matched portion of the URL.
Hooking into the Lifecycle with useEffect

Hooking into the Lifecycle with useEffect The useEffect hook accepts a
function, which it will run after each render of the function component by
default.
The useEffect hook can be used to simulate the componentDidMount(),
componentDidUpdate(), and componentWillUnmount() lifecycle methods in
function components.
The purpose of useEffect is to allow you to run imperative code that may have
side effects inside a function component
Using the Default useEffect Behavior

When you run the component in Listing 11-3, it will count each time the
function passed to useEffect runs and log the current count to the browser’s
JavaScript console
Customizing useEffect

Since this component doesn’t use state or accept any props, there’s no reason
for it to re-render, so the timer will continue to increment and log a higher
number each second for as long as the component is mounted in the browser
window.

if you want to create a game that runs a timer to test how quickly you can click
the button? One way to do this would be to only start the timer after the
component first mounts, rather than after every render
Passing an empty array as the second argument of useEffect causes it to
simulate the behaviour of the componentDidMount() lifecycle method, and
makes it a good place to put fetch requests for data that won’t change during
the life of the component, for example.
But, what if you wanted to change the game so that the timer could be
restarted when the user wants, or when the count gets up to a certain
number, for example? What you need is to conditionally run useEffect. To do
this, you can make useEffect depend on one or more values that will
determine when it runs
A number guessing game with useState

You might also like