Module5
Module5
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.
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.
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.
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.
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:
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
➤ 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