0% found this document useful (0 votes)
26 views9 pages

React Router Navigation for SPAs

Here are the steps to complete the song selection example: 1. Add state variables to track the playing status of each sound: ``` const [playing1, setPlaying1] = useState(false); const [playing2, setPlaying2] = useState(false); ``` 2. Create toggle functions for each sound: ``` function toggle1() { if(playing1) { bird1.pause(); } else { bird1.play(); } setPlaying1(!playing1); } function toggle2() { if(playing2) { bird2.pause(); } else { bird2.play();

Uploaded by

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

React Router Navigation for SPAs

Here are the steps to complete the song selection example: 1. Add state variables to track the playing status of each sound: ``` const [playing1, setPlaying1] = useState(false); const [playing2, setPlaying2] = useState(false); ``` 2. Create toggle functions for each sound: ``` function toggle1() { if(playing1) { bird1.pause(); } else { bird1.play(); } setPlaying1(!playing1); } function toggle2() { if(playing2) { bird2.pause(); } else { bird2.play();

Uploaded by

saby abby
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Navigation -React Router

In this reading, you’ll learn about the differences between traditional web pages and React-powered
web pages (SPAs – single page applications).

Once you understand the difference between these two ways of building web pages, you will be able
to understand the necessary difference between how navigation works in traditional web apps
versus how it works in modern SPA websites.

Before Single-Page Apps


Before the advent of modern JavaScript frameworks, most websites were implemented as multi-page
applications. That is, when a user clicks on a link, the browser navigates to a new webpage, sends a
request to the web server; this then responds with the full webpage and the new page is displayed in
the browser.

This can make your application resource intensive to the Web Server. CPU time is spent rendering
dynamic pages and network bandwidth is used sending entire webpages back for every request. If
your website is complex, it may appear slow to your users, even slower if they have a slow or limited
internet connection.

To solve this problem, many web developers develop their web applications as Single Page
Applications.

Single-Page Apps
You’re using many Single Page Applications every day. Think of your favorite social network, or
online email provider, or the map application you use to find local businesses. Their excellent user
experiences are driven by Single Page Applications.

A Single Page Application allows the user to interact with the website without downloading entire new
webpages. Instead, it rewrites the current webpage as the user interacts with it. The outcome is that
the application will feel faster and more responsive to the user.

How Does a Single-Page App Work?


When the user navigates to the web application in the browser, the Web Server will return the
necessary resources to run the application. There are two approaches to serving code and
resources in Single Page Applications.

1. When the browser requests the application, return and load all necessary HTML, CSS and
JavaScript immediately. This is known as bundling.
1. When the browser requests the application, return only the minimum HTML, CSS and
JavaScript needed to load the application. Additional resources are downloaded as required
by the application, for example, when a user navigates to a specific section of the application.
This is known as lazy loading or code splitting.
Both approaches are valid and are used depending on the size, complexity and bandwidth
requirements of the application. If your application is complex and has a lot of resources, your
bundles will grow quite large and take a long time to download – possibly ending up slower than a
traditional web application!

Once the application is loaded, all logic and changes are applied to the current

webpage. Let’s look at an example.

An Example of a Single-Page App


Imagine there is a webpage that has a Label and a Button. It will display a random movie name
when the button is clicked.

In a traditional website, when the button is clicked, the browser will send a POST request to the web
server. The web server will return a new web page containing the button and movie name, and the
web browser renders the new page.

In a Single Page Application, when the button is clicked, the browser will send a POST request to a
web server. The web server will return a JSON object. The application reads the object and updates
the Label with the movie name.

See, more efficient!

But what if we need to have multiple pages with different layouts in our application?

Let’s look at another example.

Practical Differences Between Single-Page Apps and


Multi-Page Apps
You have a web application that has a navigation bar on top and two pages. One page shows the
latest news, and the other shows the current user’s profile page. The navigation bar contains a link
for each page.
In a traditional website, when the user clicks the Profile link, the web browser sends the request to
the web server. The web server generates the HTML page and sends it back to the web browser.
The web browser then renders the new web page.

In a Single Page Application, different pages are broken into templates (or views). Each view will
have HTML code containing variables that can be updated by the application.

The web browser sends the request to the web server, and the web server sends back a JSON
object. The web browser then updates the web page by inserting the template with the variables
replaced by the values in the JSON object.

Anchor Tag Elements in Single-Page Elements A


single-page application can’t have regular anchor tag elements as a traditional web app can.

The reason for this is that the default behavior of an anchor tag is to load another HTML file from a
server and refresh the page. This page refresh is not possible in a SPA that's powered by a library
such as React because a total page refresh is not the way that a SPA works, as explained earlier in
this lesson item.

Instead, a SPA comes with its own special implementation of anchor tags and links, which only give
an illusion of loading different pages to the end user when in fact, they simply load different
components into a single element of the real DOM into which the virtual DOM tree gets mounted and
updated.

That's why navigation in a single-page app is fundamentally different from its counterpart in a
multi-page app. Understanding the concepts outlined in this lesson item will make you a more
well-rounded React developer.
You need to install React Router dom and use its functionalities ��

[Link]
Run this command:Step 1:

Npm i react-router-dom@6

Step 2:

Import Browser Router and wrap it arround [Link] in [Link] file

<Browser-Router>

<App />

</Browser-Router>

Step 3:

Import in [Link]

{Routes,Route,Link} from reatcrouter-dom

Now we use Route

<Routes >

<Route path =”/” element ={<Homepage />} />

<Route path =”/about-me” element ={<About Me/>} />

<Routes />

Step 4: Replace the anchor links

<Link to “/” className="nav-item">Homepage</Link>

Task
Your goal is to add another link to the existing code. This link should show a brand new component,
named Contact.
Steps
Step 1
Install the react-router package. Run npm install react-router-dom@6.

Step 2
Add a new file, [Link], to the root of the src folder.

Step 3

Inside the [Link] file, add an ES5 function, named Contact. Add the export default
Contact after the Contact function's closing curly brace.

Step 4
Inside the body of the Contact function, add a return statement with the following code:
<h1>Contact Little Lemon on this page.</h1>.

Step 5
Inside the [Link] file, import the newly-built Contact component.

Step 6
Inside the [Link] file's App function's return statement, locate the nav element, and inside of it, add
another <Link> element, with the to attribute pointing to "/contact", the className set to
"nav-item", and the the text inside the Link element's opening and closing tags set to Contact.

Step 7
Inside the Routes element, add a third route, with the path attribute pointing to "/contact", and
the element attribute set to {<Contact />}.
Step 8
Save all your changes and view your updates in the served app. You should have three links in the
top navbar, and the third link should be Contact. Once you click the link, the sentence "Contact
Little Lemon on this page" should replace whatever other content was under the navbar previously

Media packages
In this reading, you’ll learn how to install the reactjs-media npm package.

You can find this package on the [Link] website at the following URL:

[Link]

To install this package you'll need to use the following command in the terminal:

npm install react-player

Once you have this package installed, you can start using it in your project.

There are a few ways that you can import and use the installed package. For example, to get the
entire package's functionality, use the following import:

import ReactPlayer from "react-player";

If you are, for example, only planning to use videos from a site like YouTube, to reduce bundle size,
you can use the following import:

import ReactPlayer from "react-player/youtube";

Here’s an example of using the react-player packaged in a small React app:


import React from "react";
import ReactPlayer from "react-player/youtube";

const App = () => {


return (
<div>
<MyVideo />
</div>
);
};

const MyVideo = () => {


return (
<ReactPlayer url='[Link] />
);
};

export default App;

Song selection Example

Task
Say you are working on a website that allows visitors to play bird sound by pressing buttons.
The user interface is set up so that when a user presses a button it will start playing the bird
sounds. Alternatively, if the bird sound is already playing, clicking on the button will pause it.
Upon a subsequent click on the button, the sound should continue to play from where it was
paused.

Additionally, you need to add multiple buttons for multiple bird sound mp3 tracks.

Most of the app is already completed, and to finish this task, you only need to add in a few
remaining bits and pieces.
import React from "react";

function App() {

const bird1 = new Audio(

"[Link]
Caspian_Tern_XC432679.mp3"
);

const bird2 = new Audio(

"[Link]
Caspian_Tern_XC432881.mp3"
);

function toggle1() {
if ([Link]) {
[Link]();
} else {
[Link]();
}
};

return (
<div>
<button onClick={toggle1}>Caspian Tern 1</button>
<button onClick={toggle2}>Caspian Tern 2</button>
</div>
);
}

export default App;

Step 1
In this your goal is to read through the existing code of the [Link] file, and update the second
button so that it's running the toggle2 function on a click to the second button.
Step 2
After adding the toggle2 function to the JSX expression in the second button's
onClick event-handling attribute, you should un-comment the bird2 variable on lines
9 to 11.

Step 3
Next, you need to define the toggle2 function: it should have the exact same functionality
as the toggle1 function, but it needs to work with the bird2 variable (instead of the bird1
variable as it does in the toggle1 function).

Step 4
Save and view the app in the browser.

Common questions

Powered by AI

One challenge with SPAs is managing large bundle sizes, which can offset any performance gains if not optimized. Initial load times can be slower if the entire bundle must be downloaded at once. Additionally, SPAs rely heavily on JavaScript, which could result in issues on browsers with limited JS support or users with disabled JS. Furthermore, bookmarking specific pages within an SPA can be more complex, as traditional URL changes are not apparent .

To incorporate a YouTube video into a React component using ReactPlayer, follow these steps: 1) Install the react-player package via npm, 2) Import ReactPlayer from 'react-player/youtube', 3) Use the ReactPlayer component in your component's return method, setting the 'url' prop to the desired YouTube video URL, and 4) Implement any desired controls such as play, pause, or volume adjustments. Using ReactPlayer facilitates a smooth integration of video content, supports a wide range of media platforms, and abstracts complex media handling, offering a consistent interface for various media types without managing HTML5 media elements manually .

Lazy loading improves performance in SPAs by delaying the loading of non-essential resources until they are actually needed by the user. By initially loading only the minimal amount of resources necessary to display the initial view, lazy loading reduces the initial load time and bandwidth usage. As the user navigates through the application, additional resources are loaded on the fly, providing a balance between performance and resource availability. This technique prevents a large upfront download that could negatively impact the user's experience, especially on slower networks .

In a traditional multi-page app, navigation typically involves sending a request to the server for a new page whenever a link is clicked. The server processes the request, generates the HTML for the new page, and the browser renders it entirely anew. For example, clicking the Profile link in a news site would trigger a full page request-and-load cycle. In contrast, a SPA uses in-browser techniques to manage navigation, loading new content into the existing page structure without a full page reload. For instance, within a SPA news site, clicking the Profile link only swaps in the profile content by interacting with the existing DOM elements, thereby providing a fluid user experience .

One of the primary benefits of using SPAs is their improved user experience and efficiency. SPAs allow users to interact with the web application without downloading entire new webpages because they rewrite the current webpage as the user interacts with it, making the application feel faster and more responsive. This contrasts with traditional multi-page applications where each user interaction typically requires loading an entirely new page, leading to slower performance, especially over limited or slow internet connections .

In SPAs, traditional anchor tags are limited because their default behavior is to request new pages from the server, which does not align with the SPA model of avoiding page reloads. Instead, frameworks like React use custom implementations of anchor tags, which navigate between different components within the SPA without causing a full page refresh. This approach enables seamless transitions and preserves the single-page application model but requires careful handling to manage browser history and URL states .

To add a new route to a React application using React Router, follow these steps: 1) Install the react-router-dom package, 2) Create a new component file and export the component, 3) Import the component into the main application file, 4) Add a Link element for navigation in the application's navigation bar, pointing to the new route, 5) Add a Route element to the Routes component, specifying the path and the new component to display when the path is accessed, and 6) Save changes and verify the new route functions as expected in the app .

Bundling and lazy loading are two different approaches to resource management in SPAs. Bundling involves loading all necessary HTML, CSS, and JavaScript resources upfront when the application is initially loaded. This approach can result in slower initial load times due to large bundle sizes but will provide faster navigation thereafter. On the other hand, lazy loading involves loading only essential resources initially and downloading additional resources on demand as the user interacts with the application. This helps improve initial load times and optimizes resource usage but may lead to delays when accessing new parts of the application .

React Router enhances the functionality of a SPA by allowing for the implementation of dynamic routing in a React application. Instead of reloading the whole page when accessing different sections of the application, React Router enables seamless navigation by loading components dynamically into a single DOM, creating an illusion of moving between different pages. This approach maintains the efficiency and responsiveness of the SPA .

The ReactPlayer package simplifies media management in React applications by allowing developers to easily embed and control media players directly in their components. It supports various media sources, such as YouTube, and provides a consistent API to control playback, such as playing, pausing, and seeking within the media, without manually managing complex HTML5 media elements. By importing only the needed functionality, developers can also reduce the application's bundle size .

You might also like