Router ReactJS — GeeksforGeeks (2024)

React routerato standardowa biblioteka do routingu w React. Umożliwia nawigację między widokami różnych komponentów w aplikacji React, umożliwia zmianę adresu URL przeglądarki i utrzymuje synchronizację interfejsu użytkownika z adresem URL.
Stwórzmy prostą aplikację do Reacta, aby zrozumieć, jak działa React Router. Aplikacja będzie zawierała trzy komponenty: komponent domowy, komponent o komponencie oraz komponent kontaktowy. Do poruszania się między tymi komponentami użyjemy React Router.

Konfigurowanie aplikacji React:Stwórz aplikację React używająctwórz-reaguj-aplikacjęi nazwijmy tomaniacy.

Notatka:Jeśli wcześniej instalowałeś globalnie aplikację create-react-app przez npm, bezpośrednio użyj poniższego polecenia:

npx maniacy tworzenia-reagowania-aplikacji

Router ReactJS — GeeksforGeeks (1)
Twoje środowisko programistyczne jest gotowe. Zainstalujmy teraz React Router w naszej aplikacji.

Instalacja React Routera:React Router można zainstalować przeznpw Twojej aplikacji React. Wykonaj poniższe czynności, aby zainstalować Router w swojej aplikacji React:

  • Krok 1: płyta CDdo katalogu projektu, tjmaniacy.
  • Krok 2:Aby zainstalować React Router, użyj następującego polecenia:

npm install – -save react-router-dom lub npm i react-router-dom
(to zaktualizowane polecenie)

Router ReactJS — GeeksforGeeks (2)
Po zainstalowaniu react-router-dom dodaj jego komponenty do swojej aplikacji React.

Dodawanie komponentów routera React:Główne komponenty React Routera to:

  • PrzeglądarkaRouter:BrowserRouter to implementacja routera, która wykorzystuje interfejs API historii HTML5 (pushState, replaceState i zdarzenie popstate), aby zapewnić synchronizację interfejsu użytkownika z adresem URL. Jest to komponent nadrzędny, który jest używany do przechowywania wszystkich pozostałych komponentów.
  • Trasy:Jest to nowy komponent wprowadzony w v6 i uaktualnienieczęść. Główne zalety Routes Over Switch to:
    • Względnys i s
    • Trasy są wybierane na podstawie najlepszego dopasowania, a nie pokonywane w kolejności.
  • Trasa:Trasa to warunkowo wyświetlany komponent, który renderuje interfejs użytkownika, gdy jego ścieżka jest zgodna z bieżącym adresem URL.
  • Połączyć:Komponent Link służy do tworzenia linków do różnych tras i implementacji nawigacji po aplikacji. Działa jak HTMLznacznik kotwicy.

Aby dodać komponenty React Router do swojej aplikacji, otwórz katalog projektu w edytorze, którego używasz i przejdź do niegoaplikacja.jsplik. Teraz dodaj poniższy kod w pliku app.js.

import {

BrowserRouter jako Router,

Trasy,

Trasa,

Połączyć

} z„React-router-dom”;

Notatka:BrowserRouter jest aliasem Routera.

Korzystanie z routera reagowania:Aby użyć React Router, najpierw utwórzmy kilka komponentów w aplikacji React. W katalogu projektu utwórz folder o nazwieczęśćwewnątrz folderu src, a teraz dodaj 3 pliki o nazwiestrona główna.js,o.jsIkontakt.jsdo folderu komponentu.
Router ReactJS — GeeksforGeeks (3)
Dodajmy trochę kodu do naszych 3 komponentów:

  • kontakt.js:

    importuj Reaguj z'reagować';

    funkcjonować Kontakt (){

    powrót

    Znajdziesz nas tutaj:

    GeeksforGeeks

    5. i 6. piętro, Royal Kapsons, A-118,

    Sector- 136, Noida, Uttar Pradesh (201305)

    }

    eksportdomyślny Kontakt;

  • Teraz dołączmy do aplikacji komponenty React Router:

    • PrzeglądarkaRouter:Dodaj BrowserRouter aliasowany jako Router do pliku app.js, aby opakować wszystkie pozostałe komponenty. BrowserRouter jest komponentem nadrzędnym i może mieć tylko jedno dziecko.

      klasa Aplikacja rozszerza komponent {

      renderowanie() {

      powrót (

      „Aplikacja”>

      );

      }

      }

    • Połączyć:Utwórzmy teraz linki do naszych komponentów. Komponent łącza używaDoprop, aby opisać lokalizację, do której powinny prowadzić linki.

      „Aplikacja”>

      • "/">Strona główna

      • "/o">O nas

      • "/kontakt">Skontaktuj się z nami

      Teraz uruchom aplikację na lokalnym hoście i kliknij utworzone łącza. Zauważysz, że adres URL zmienia się zgodnie z wartością wDorekwizyty komponentu Link.
      Router ReactJS — GeeksforGeeks (4)

    • Trasa:Komponent trasy pomoże nam teraz ustalić powiązanie między interfejsem użytkownika komponentu a adresem URL. Aby uwzględnić trasy do aplikacji, dodaj poniższy kod do pliku app.js.

      '/' element={< Strona główna />}>

      '/o' element={< Informacje />}>

      '/kontakt' element={< Kontakt />}>

      Komponenty są teraz połączone, a kliknięcie dowolnego łącza spowoduje wyświetlenie skojarzonego z nim komponentu.
      Router ReactJS — GeeksforGeeks (5)
      Spróbujmy teraz zrozumieć rekwizyty związane z komponentem Trasa.

      Notatka:Domyślnie trasy są włączane, co oznacza, że ​​więcej niż jeden komponent Route może pasować do ścieżki URL i renderować w tym samym czasie. Jeśli chcemy wyrenderować pojedynczy komponent, musimy użyćtrasy.

    • Trasy:Aby wyrenderować pojedynczy komponent, zawiń wszystkie trasy w komponencie Routes.

      '/' element={< Strona główna />}>

      '/o' element={< Informacje />}>

      '/kontakt' element={< Kontakt />}>

      Przełącz grupowanie kilku tras, iteruj po nich i znajdź pierwszą, która pasuje do ścieżki. W ten sposób renderowany jest odpowiedni komponent ścieżki.

    • Po dodaniu wszystkich komponentów oto nasz kompletny kod źródłowy:

      importuj React, { Komponent } z'reagować';

      importuj {BrowserRouter jako Router, Trasy, Trasa, Łącze} z„React-router-dom”;

      importuj dom z„./komponent/strona główna”;

      importuj informacje z„./komponent/informacje”;

      importuj kontakt z„./komponent/kontakt”;

      import'./App.css';

      klasa Aplikacja rozszerza komponent {

      renderowanie() {

      powrót (

      „Aplikacja”>

      „Nagłówek aplikacji”>

    • "/">Strona główna

    • "/o">O nas

    • "/kontakt">Skontaktuj się z nami

      '/' element={< Strona główna />}>

      '/o' element={< Informacje />}>

      '/kontakt' element={< Kontakt />}>

    • );

      }

      }

      eksportdomyślny Aplikacja;

      Teraz możesz kliknąć linki i przejść do różnych komponentów. React Router zapewnia synchronizację interfejsu użytkownika aplikacji z adresem URL.
      Router ReactJS — GeeksforGeeks (7)
      Router ReactJS — GeeksforGeeks (8)
      Router ReactJS — GeeksforGeeks (9)
      Wreszcie udało nam się zaimplementować nawigację w naszej aplikacji React za pomocą React Router.


      Ostatnio zaktualizowany :10 maja 2023 r

      Jak artykuł

      Zapisz artykuł

      Router ReactJS — GeeksforGeeks (2024)

      FAQs

      What is a Router in React JS? ›

      React Router is a JavaScript framework that lets us handle client and server-side routing in React applications. It enables the creation of single-page web or mobile apps that allow navigating without refreshing the page.

      Read On
      How many types of routing are in React JS? ›

      On the basis of the part of the URL that the router will use to track the content that the user is trying to view, React Router provides three different kinds of routers: Memory Router. Browser Router. Hash Router.

      Discover More Details
      What is the difference between react Router and react dom? ›

      React Router excels at handling navigation and routing within your application, while React DOM focuses on rendering your React components into the DOM. Depending on your project requirements, you can choose between the two or even use them together for a comprehensive solution.

      Continue Reading
      Which Router is best for react? ›

      React Router has stood the test of time and continues to be a reliable choice for many react developers. However, TanStack Router is proving to be a formidable alternative, especially for those seeking type safety, built-in caching, and structural sharing.

      See Details
      Is react router a framework or library? ›

      React Router is a lightweight, fully-featured routing library for the React JavaScript library. React Router runs everywhere that React runs; on the web, on the server (using node.js), and on React Native.

      Find Out More
      What are the advantages of routing in React? ›

      Uses of React Router

      It allows users to switch between views without refreshing the entire page. Dynamic Routing: React Router supports dynamic routing, which means routes can change based on the application's state or data, making it possible to handle complex navigation scenarios.

      Tell Me More
      What is the difference between normal routing and React routing? ›

      React Router enables "client side routing". In traditional websites, the browser requests a document from a web server, downloads and evaluates CSS and JavaScript assets, and renders the HTML sent from the server. When the user clicks a link, it starts the process all over again for a new page.

      Show Me More
      Do I really need a React Router? ›

      Although it is one of the best solutions for building websites, React does not include many advanced features or routing by default. Therefore, React Router is an excellent choice of navigation for these single-page applications to render multiple views.

      Explore More
      Should I learn React Router or Next js? ›

      Next. js is worth considering over plain React when you need server-side rendering, static site generation, simplified routing, improved performance, or built-in features for your web application. However, if your application requires high customization, sticking with React alone might be more appropriate.

      Continue Reading
      When should I use React-Router-DOM? ›

      If you are writing an application that will run in the browser, you should instead install react-router-dom . Similarly, if you are writing a React Native application, you should instead install react-router-native . Both of those will install react-router as a dependency.

      Show Me More

      What can I use instead of react router? ›

      Hookrouter produces the same outcome as the React Router but in a more streamlined and lightweight manner. Syncfusion React UI components are the developers' choice to build user-friendly web applications.

      Read The Full Story
      What is the most used react router? ›

      React Router is the most widely used React routing library, with over 49,000 stars on GitHub. It provides a powerful and flexible routing solution for React applications, allowing developers to manage client-side routing in a declarative and efficient way.

      See Details
      Why Router is used in react? ›

      ReactJS Router is mainly used for developing Single Page Web Applications. React Router is used to define multiple routes in the application. When a user types a specific URL into the browser, and if this URL path matches any 'route' inside the router file, the user will be redirected to that particular route.

      Get More Info Here
      What is Router in JavaScript? ›

      The Javascript router aids in refactoring your application. If you change the structure of your URLs or parameter names your Javascript gets automatically updated to use that new structure.

      Continue Reading
      What is in a Router? ›

      A router is a device that connects two or more packet-switched networks or subnetworks. It serves two primary functions: managing traffic between these networks by forwarding data packets to their intended IP addresses, and allowing multiple devices to use the same Internet connection.

      View More
      What is switch and Router in react? ›

      Router components render inclusively of all route matches. The Switch component will render exact matches, and only the exact match. This makes it ideal for these nested scenarios.

      View Details
      Is react router a server? ›

      React Router is a JavaScript library used to handle client and server-side routing in React applications.

      See More
      Top Articles
      Required Firewall Exceptions for Teredo - Win32 apps
      STEP 13 Test DirectAccess Connectivity from Behind a NAT Device
      Toa Guide Osrs
      Radikale Landküche am Landgut Schönwalde
      Prosper TX Visitors Guide - Dallas Fort Worth Guide
      Women's Beauty Parlour Near Me
      Miles City Montana Craigslist
      Gameplay Clarkston
      CSC error CS0006: Metadata file 'SonarAnalyzer.dll' could not be found
      OnTrigger Enter, Exit ...
      4Chan Louisville
      Obituary | Shawn Alexander | Russell Funeral Home, Inc.
      Hssn Broadcasts
      Beau John Maloney Houston Tx
      Used Drum Kits Ebay
      Tnt Forum Activeboard
      iZurvive DayZ & ARMA Map
      What Is Vioc On Credit Card Statement
      Craigslist Prescott Az Free Stuff
      Vernon Dursley To Harry Potter Nyt Crossword
      Craigslist Dubuque Iowa Pets
      Kirk Franklin Mother Debra Jones Age
      Bidrl.com Visalia
      Dal Tadka Recipe - Punjabi Dhaba Style
      Unity Webgl Car Tag
      The Powers Below Drop Rate
      Stephanie Bowe Downey Ca
      Ugly Daughter From Grown Ups
      Craigslist Dallastx
      AP Microeconomics Score Calculator for 2023
      Staar English 1 April 2022 Answer Key
      Pitchfork's Top 200 of the 2010s: 50-1 (clips)
      Toth Boer Goats
      Zasilacz Dell G3 15 3579
      Atlanta Musicians Craigslist
      Lcwc 911 Live Incident List Live Status
      888-822-3743
      Mississippi weather man flees studio during tornado - video
      Nina Flowers
      Isabella Duan Ahn Stanford
      Silicone Spray Advance Auto
      Yale College Confidential 2027
      Skyward Cahokia
      N33.Ultipro
      Terrell Buckley Net Worth
      Minecraft: Piglin Trade List (What Can You Get & How)
      Makes A Successful Catch Maybe Crossword Clue
      Treatise On Jewelcrafting
      Raley Scrubs - Midtown
      Black Adam Showtimes Near Cinemark Texarkana 14
      Aspen.sprout Forum
      Laurel Hubbard’s Olympic dream dies under the world’s gaze
      Latest Posts
      What Tyres Should You Choose For A Quiet Drive & How Do They Work? - etyres blog
      Teredo Components - Win32 apps
      Article information

      Author: Merrill Bechtelar CPA

      Last Updated:

      Views: 6269

      Rating: 5 / 5 (50 voted)

      Reviews: 89% of readers found this page helpful

      Author information

      Name: Merrill Bechtelar CPA

      Birthday: 1996-05-19

      Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

      Phone: +5983010455207

      Job: Legacy Representative

      Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

      Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.