Document Details

Uploaded by Deleted User

Tags

React Router web development JavaScript single page applications

Summary

This document provides a tutorial on using React Router for client-side routing in single page applications. It covers installing React Router, different components, static routing, and creating dynamic routes. The tutorial includes code examples and explanations.

Full Transcript

REACT ROUTER create-react-app provides a great starting point for React applications, but it doesn't come equipped with built-in page routing capabilities. React Router stands as the primary choice for routing in React applications, distinguishing itself as one of the most prominent...

REACT ROUTER create-react-app provides a great starting point for React applications, but it doesn't come equipped with built-in page routing capabilities. React Router stands as the primary choice for routing in React applications, distinguishing itself as one of the most prominent libraries built atop React. React Router enables "Client Side Routing". Client-side routing is a paradigm shift from traditional web applications. It allows your app to update the URL from a link click without making another request for another document from the server. Instead, your app can immediately render some new UI and make data requests with fetch to update the page with new information. React Router, thus, allows developers to conditionally display components based on matching defined routes, ensuring a seamless user experience. Refer to Figure 1 below to visualize how your UI should appear after integrating React Router: Figure 1. Shopping Cart Navigation Bar Integration Using React Router Learning objectives: - Understand the importance of client-side routing in Single Page Applications (SPAs). (Differentiate between client-side routing and server-side routing.) - Set up and integrate react-router-dom into a React project. - Recognize the primary components provided by React Router. - Configure dynamic routes using route parameters. - Extract route parameters using the useParams hook. - Implement programmatic navigation using the useNavigate hook. 1. Installing React Router: - Open Your Project: Navigate to the directory where you have your shopping cart React app saved. - Open Your App in a Code Editor. - Your development environment is ready. Let us now install React Router in our application. React Router can be installed via npm in your React application. Follow the steps given below to install Router in your React application: npm install react-router-dom we are using React Router v6. If you are upgrading from v5, you will need to use the @latest flag: npm react-router-dom@latest - After installation is complete, you can verify that react-router-dom has been added to your project by checking the package.json file. Under the dependencies section, you should see "react-router-dom" listed with its version number. 2. React Router Components: After installing react-router-dom, lets add its components to your React application. The main Components of React Router are: To provide a navigation experience similar to traditional multi-page websites (where every navigation action leads to an actual page load from the server, visibly altering the URL and updating the browser's history), SPAs harness the HTML5 history API to modify the browser's history and the displayed URL without triggering a page reload. This gives users the perception of navigating between different "pages" even though they're still on the same web page. - component provides the routing capabilities to its child components ensuring that navigation within the SPA reflects accurately in the browser's history. Consequently, the browser's back and forward buttons operate seamlessly, allowing users to navigate through the history of "pages" they've visited within the SPA. - : is a component introduced in React Router version 6. It serves as a container for one or more components and is responsible for rendering the first that matches the current location. - : is the conditionally shown component that renders some UI when its path matches the current URL. It establishes the link between component’s UI and the URL. - : is an element that lets the user navigate to another page by clicking on it. It renders an anchor () tag in the DOM which, when clicked, changes the URL without causing a full page reload. It uses the “to” prop to specify the target path of the navigation. To add React Router components in your application, go to App.js file and ensure you include the following import statement: import { BrowserRouter, Routes, Route } from "react-router-dom"; 3. Using React Router To create an application with multiple page routes, let us first create few components in the react application. - Within your components folder, establish five new files with the following names: NavigationBar.js, Home.js, About.js, Customers.js and ProductDetails.js. A. Static Routing - Each of these files: Home.js, About.js and Customers.js should house a foundational React component, About.js import React from 'react' export default function About() { return ( About ) } Home.js import React from 'react' function Home() { return ( Home ) } export default Home 1. Create a NavigationBar Component: NavigationBar.js a. Start by importing the specific Navbar component, as highlighted in the figure shown below, from 'react-bootstrap'. b. Create Components: Now, let us include React Router components to the application. Use the Link component from react-router-dom to create navigable links in your app. The to prop determines the route the link will navigate to. Home c. Style the Components: Start by styling the Bootstrap Nav component that wraps around the Link components so that the links are evenly spaced and have a larger font size. Define a LinkStyle constant to style the Link components. This ensures that the links have no underlines, are white in color, and have a white border to their right. 2. Adding a Router a. The first thing to do is create a Browser Router and configure our first route. This will enable client-side routing for our web app. b. Creating routes Configure the Home, About, Customers and ListOfProducts routes and render them to match their URL. path: Path specifies a pathname we assign to our component. element: It refers to the component which will render on matching the path. When a Route’s path matches the current browser URL, the associated React element will render. App.js return ( // Implement Route components that will establish the link between // component’s UI and the URL. ); } export default App; A. Dynamic Routing 1. Update the CardItem Component - Start by importing the specific Button with a Badge component, as highlighted in the figure shown below, from 'react-bootstrap'. - Provide the appropriate changes so it displays the same structure as in figure 3. - Create an onClick event for the button and attach to it a showDetails function. - To navigate to a product's details page when clicked, define a showDetails function that uses the useNavigate hook. useNavigate hook introduced in React Router v6, is specifically tailored for navigation. It returns a function that lets you navigate programmatically to other routes in response to certain events or actions. CardIItem.js const navigate=useNavigate(); const showDetails=()=>{ //Navigate to a specific product's page }; ❖ Configure dynamic routes using route parameters. - Define a dynamic Route in your application to display details of a specific product based on its id using the ProductDetails component. Dynamic Segment - A segment of a path pattern that is dynamic, meaning it can match any values in the segment. For example the pattern /products/:id will match URLs like /products/1. App.js ❖ Create the ProductDetails Component: ProductDetails.js ProductDetails component displays details for a specific product based on its id from the URL. Utilize the CardItem component to present these details and showcase additional information, more specifically, the brand of the product. - Import the useParams hook from React Router, which allows you to access dynamic parts of the URL path. These dynamic parts are often referred to as "parameters" or "params", and they allow you to capture values directly from the URL. const { id } = useParams(); useParams hook returns an object where the keys are the names of the dynamic segments and the values are the corresponding parts of the actual URL. It's important to note that the values captured by useParams are always strings, regardless of their appearance in the URL. If you need them to be a different type (like a number), you'd have to convert them yourself. - Imports the CardItem component, which will be used to display the product details. - Search the product array to find the product object with the matching id extracted from the URL. o Use the find method to retrieve the product with the corresponding id from the product array. find method is a built-in JavaScript function for arrays. It iterates over each element in the array and returns the first element that satisfies the provided testing function. If no element satisfies the testing function, it returns undefined. - Render the CardItem component, passing the found product and setting the details prop to true. This indicates that detailed information should be displayed for the product. ❖ Display Product Details CardItem.js - Within the CardItem component, conditionally render the product's brand as a Card.Title element only if the details prop is provided and set to true. Figure 2. Dynamic Routing Components are linked now and clicking on any link will render the component associated with it. Now, run your application on the local host and click on the links you created. You will notice the url changing according to the value in to props of the Link component. Now, you can click on the links and navigate to different components. React Router keeps your application UI in sync with the URL. You have successfully implemented navigation in our React application using React Router.

Use Quizgecko on...
Browser
Browser