Cookie Consent by Free Privacy Policy Generator Aktuallisiere deine Cookie Einstellungen ๐Ÿ“Œ Exploring React Router 6


๐Ÿ“š Exploring React Router 6


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

Working of the React Router 6

Introduction

Single-page applications (SPAs) with multiple pages need to have a mechanism of routing to navigate between those different views without refreshing the whole webpage. We can dynamically change application views by switching the app state with conditional rendering, but in most scenarios, we need to sync the application URL with views.

What is React Router?

React Router is a complete solution that can help in routing activities within React applications. This feature comes with pre-built components, hooks, and helper functions which are essential when coming up with up-to-date formation strategies. React Router project has come up with two different packages that will help you integrate routing either in your web app or any other app that uses React.

React Router v6 includes modern features such as relative nested routes, optimistic UI, and developer-friendly hooks.

Why do we use React Router for routing?

Traditional web applications with multiple pages commonly have several separate files that display different views, but modern single page applications (SPAs) use video-like scenes. This makes it necessary to use routing in order to switch between different URLs. For any React application requirement, you donโ€™t always need an external library but with regards to routing, this may not be true, routing needs are complex and you must use a router library to meet them.

React Router is the most popular and feature-rich routing library for React-based SPAs. It has a small footprint, a simple API, and well-written documentation, allowing any React developer to implement routing productively in any React app.

BrowserRouter

The BrowserRouter serves as a container which envelops the entire application and manages the routing within. In this case, you can define routes, switch between them, and interact with different URL paths in single-page application (SPA) mode but with no need for excessive page reloading.

Routes

Routes is an element container that displays the first child route that matches the current location. This has replaced the previous Switch component and provides a way to group all route definitions together.

Route

Used to define individual route. Each individual Route component specifies a path and the component to render when the URL corresponds to that path. The path prop defines the URL path, and the element prop specifies the component to render.

export default function App() {
  return (
    <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/user/:username" element={<User />} />
          <Route path="*" element={<NotFound />} />
        </Routes>
    </BrowserRouter>
  );
}


Let's work on the application.

First, let's set up a new React application. If you haven't already, install Node.js and npm. Then, create a new React app using Create React App:

npx create-react-app react-router-example
cd react-router-example

Next, install React Router:

npm install react-router-dom

Creating Components

We'll create four components for our example: Home, About, User, and NotFound.

  • Home will serve as the landing page and provide navigation links.
  • About will display some information about the application.
  • User will display user-specific information based on the URL parameter.
  • NotFound will be a fallback component for any unmatched routes.

Let's start by creating these components.

Home Component

Create a file named Home.js inside the src/components directory and add the following code:

import React from 'react';
import { Link } from 'react-router-dom';
import './Home.css';

const Home = () => {
  return (
    <div className="home">
      <h2>Home Page</h2>
      <nav>
        <ul>
          <li><Link to="/" end>Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/user/john">User John</Link></li>
          <li><Link to="/user/jane">User Jane</Link></li>
        </ul>
      </nav>
    </div>
  );
};

export default Home;

Link

The Link component helps build interactive links in React applications for navigating to other routes without refreshing the page so that your app can function like a single page application (SPA).

  • โ€œtoโ€ Prop should be set as the route to follow when navigating. It can either be a single path in a string form or an object for advanced navigation that includes state or search params.
  • When a hyperlink is clicked, it renders the new component without reloading the entire page
About Component

Create a file named About.js inside the src/components directory and add the following code:

import React from 'react';

const About = () => {
  return (
    <div>
      <h2>About Page</h2>
      <p>This is the About page of our React Router example.</p>
    </div>
  );
};

export default About;

User Component
Create a file named User.js inside the src/components directory and add the following code:

import React from 'react';
import { useParams } from 'react-router-dom';

const User = () => {
  const { username } = useParams();

  return (
    <div>
      <h2>User Page</h2>
      <p>Username: {username}</p>
    </div>
  );
};

export default User;
useParams

useParams is a hook that enables you to get the dynamic parameters of the current route, which are usually defined in the route paths and later used to capture URL values.

  • The part of the route defined with : (e.g., :id in /user/:id) acts as a placeholder for the dynamic value.
  • Inside the component rendered by the route, use useParams to access these dynamic values.
NotFound Component

Create a file named NotFound.js inside the src/components directory and add the following code:

import React from 'react';
import { Link } from 'react-router-dom';

const NotFound = () => {
  return (
    <div>
      <h2>Page Not Found</h2>
      <p>Sorry, the page you are looking for does not exist.</p>
      <Link to="/">Go to Home</Link>
    </div>
  );
};

export default NotFound;

Setting Up the Router in App.js

Now, let's set up the router in our main App.js file. Import the necessary components from React Router and configure the routes.

Update src/App.js with the following code:

import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import User from './components/User';
import NotFound from './components/NotFound';
import './App.css';

export default function App() {
  return (
    <BrowserRouter>
      <div className="app">
        <h1>React Router Example</h1>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/user/:username" element={<User />} />
          <Route path="*" element={<NotFound />} />
        </Routes>
      </div>
    </BrowserRouter>
  );
}

Running the Application

With everything set up, you can now start the development server to see your app in action:

npm start

Navigate to http://localhost:3000 in your browser. You should see the home page with navigation links. Clicking on the links will take you to the respective pages (About, User, etc.), and if you try to navigate to a non-existent route, you will see the NotFound component.

...



๐Ÿ“Œ This Week In React #185: React Conf, React Query, refs, Next.js after, mini-react...


๐Ÿ“ˆ 30.37 Punkte

๐Ÿ“Œ This Week In React #185: React Conf, React Query, refs, Next.js after, mini-react...


๐Ÿ“ˆ 30.37 Punkte

๐Ÿ“Œ This Week In React #146: Concurrency, Server Components, Next.js, React-Query, Remix, Expo Router, Skia, React-Native...


๐Ÿ“ˆ 29.59 Punkte

๐Ÿ“Œ ๐Ÿš€Exploring React Storybook: A Journey Through Button Components and exploring Typescriptโœ๐Ÿฝ


๐Ÿ“ˆ 28.52 Punkte

๐Ÿ“Œ Exploring React Router 6


๐Ÿ“ˆ 24.87 Punkte

๐Ÿ“Œ This Week In React #127: Nextra, React-Query, React Documentary, Storybook, Remix, Tamagui, Solito, TC39, Rome...


๐Ÿ“ˆ 22.78 Punkte

๐Ÿ“Œ This Week In React #131: useReducer, Controlled Inputs, Async React, DevTools, React-Query, Storybook, Remix, RN , Expo...


๐Ÿ“ˆ 22.78 Punkte

๐Ÿ“Œ This Week In React #139: React.dev, Remix, Server Components, Error Boundary, Wakuwork, React-Native, Bottom Sheet...


๐Ÿ“ˆ 22.78 Punkte

๐Ÿ“Œ This Week In React #142: React-Query, Million, OpenNext, Ariakit, Expo-Image, React-Three-Fiber, TS 5.1, Node.js 20, WebGPU...


๐Ÿ“ˆ 22.78 Punkte

๐Ÿ“Œ Whatโ€™s New in React 19? React Canaries, Actions, and React Compiler


๐Ÿ“ˆ 22.78 Punkte

๐Ÿ“Œ This Week In React #188 : React 19 RC0, Data Fetching, Framer Motion, Compiler, Astro, Zod, Remix, Docusaurus, React-Query...


๐Ÿ“ˆ 22.78 Punkte

๐Ÿ“Œ Handling React OTP Input Auth Web | React Native using react-otp-kit package


๐Ÿ“ˆ 22.78 Punkte

๐Ÿ“Œ Handling React OTP Input Auth Web | React Native using react-otp-kit package


๐Ÿ“ˆ 22.78 Punkte

๐Ÿ“Œ heise+ | Externe Bibliotheken fรผr React: Material-UI und React Router einbinden


๐Ÿ“ˆ 22 Punkte

๐Ÿ“Œ Mastering React Router: The Ultimate Guide to Navigation and Routing in React Apps!


๐Ÿ“ˆ 22 Punkte

๐Ÿ“Œ Implementing JWT Authentication in React with react-router


๐Ÿ“ˆ 22 Punkte

๐Ÿ“Œ React Router not working after "React app" published through GitHub actions


๐Ÿ“ˆ 22 Punkte

๐Ÿ“Œ Understanding React Routing Using React Router


๐Ÿ“ˆ 22 Punkte

๐Ÿ“Œ ๐Ÿš€Level Up Your React Apps: Mastering Client-Side Routing with React Router DOM๐Ÿฅช๐Ÿ™‚


๐Ÿ“ˆ 22 Punkte

๐Ÿ“Œ React Rooting (react-router-dom)


๐Ÿ“ˆ 22 Punkte

๐Ÿ“Œ Problem with Hash Router in react-router-dom V6.22.3


๐Ÿ“ˆ 21.22 Punkte

๐Ÿ“Œ React Router has merged with Remix, should you use a different router?


๐Ÿ“ˆ 21.22 Punkte

๐Ÿ“Œ Exploring Error Boundary in React: Enhancing Robustness and Error Handling


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring React State Management: From Simple to Sophisticated Solutions


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring React Native: A Journey into Cross-Platform Delight


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring the Best UI Component Libraries for React Native apps


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring Advanced Tools in React Development


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring โ€œData Fetching with React Server Componentsโ€ with Next.js


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring Whatโ€™s New in React 19: Actions, Async Scripts, Server Components, and More


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring React v19: Elevating User Experiences with Concurrent Mode and Suspense


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring React Hooks: Benefits, Drawbacks, and Real-World Examples


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ React Hooks: Exploring the power of `useEffect` Hook.


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring the Top Lightweight Alternatives to React in 2023


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Revolutionizing Customer Relationships: Exploring the Synergy of CRM With Chat and React.js


๐Ÿ“ˆ 18.06 Punkte

๐Ÿ“Œ Exploring useMemo in React: Optimization and Real-World Applications


๐Ÿ“ˆ 18.06 Punkte











matomo