Skip to content Skip to sidebar Skip to footer

React Router Route Causes Root App to Render Again

The author selected Artistic Commons to receive a donation as role of the Write for DOnations program.

Introduction

In React, routers aid create and navigate between the different URLs that make up your web awarding. They permit your user to motility betwixt the components of your app while preserving user land, and can provide unique URLs for these components to make them more shareable. With routers, yous can meliorate your app's user feel past simplifying site navigation.

React Router is one of the most popular routing frameworks for React. The library is designed with intuitive components to permit you lot build a declarative routing arrangement for your awarding. This means that you tin can declare exactly which of your components has a certain route. With declarative routing, yous can create intuitive routes that are man-readable, making it easier to manage your application architecture.

In this tutorial, you'll install and configure React Router, build a set of routes, and connect to them using the <Link> component. Yous'll besides build dynamic routes that collect information from a URL that you can access in your component. Finally, yous'll use Hooks to access data and other routing information and create nested routes that alive inside components that are rendered by parent routes.

By the end of this tutorial, you'll be able to add routes to whatever React project and read information from your routes and then that you can create flexible components that respond to URL data.

Prerequisites

  • Yous will need a evolution environment running Node.js; this tutorial was tested on Node.js version 10.22.0 and npm version vi.xiv.six. To install this on macOS or Ubuntu 18.04, follow the steps in How to Install Node.js and Create a Local Evolution Surround on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04.

  • A React development environment prepare with Create React App, with the non-essential boilerplate removed. To gear up this upwardly, follow Step ane — Creating an Empty Project of the How To Manage State on React Grade Components tutorial. This tutorial will employ router-tutorial as the project proper noun.

  • Y'all will exist using React components and custom Hooks throughout the tutorial. You lot tin learn about components in How To Create Custom Components in React and Hooks in How To Manage State with Hooks on React Components.

  • You will also need a basic knowledge of JavaScript, HTML, and CSS, which you tin can find in our How To Build a Website With HTML series, How To Build a Website With CSS series, and in How To Code in JavaScript.

Step one — Installing React Router

In this step, yous'll install React Router into your base project. In this project, you are going to make a small website about marine mammals. Each mammal will need a dissever component that you'll render with the router. After installing the library, you'll create a series of components for each mammal. By the cease of this pace, you'll have a foundation for rendering different mammals based on route.

To start, install the React Router package. There are ii unlike versions: a web version and a native version for use with React Native. You will install the web version.

In your terminal, use npm to install the packet:

                      
  1. npm install react-router-dom

The package will install and you lot'll receive a message such as this ane when the installation is complete. Your message may vary slightly:

                      

Output

... + react-router-dom@five.2.0 added 11 packages from 6 contributors and audited 1981 packages in 24.897s 114 packages are looking for funding run `npm fund` for details found 0 vulnerabilities

You now have the package installed. For the remainder of this stride, you'll create a series of components that will each have a unique route.

To start, make a directory for 3 dissimilar mammals: manatees, narwhals, and whales. Run the following commands:

                      
  1. mkdir src/components/Manatee
  2. mkdir src/components/Narwhal
  3. mkdir src/components/Whale

Next, create a component for each brute. Add together an <h2> tag for each mammal. In a full application, the child components tin be as complex equally y'all want. They can even import and return their own child components. For this tutorial, you'll return only the <h2> tag.

Begin with the manatee component. Open up Manatee.js in your text editor:

                      
  1. nano src/components/Manatee/Manatee.js

Then add the basic component:

router-tutorial/src/components/Manatee/Manatee.js

                      import            React            from            'react'            ;            consign            default            role            Manatee            (            )            {            render            <h2>Manatee<            /h2>            ;            }                  

Save and close the file.

Next, create a component for the narwhal:

                      
  1. nano src/components/Narwhal/Narwhal.js

Add the same bones component, changing the <h2> to Narwhal:

router-tutorial/src/components/Narwhal/Narwhal.js

                      import            React            from            'react'            ;            consign            default            function            Narwhal            (            )            {            render            <h2>Narwhal<            /h2>            ;            }                  

Save and close the file.

Finally, create a file for Whale:

                      
  1. nano src/components/Whale/Whale.js

Add the aforementioned basic component, irresolute the <h2> to Whale:

router-tutorial/src/components/Whale/Whale.js

                      import            React            from            'react'            ;            export            default            role            Whale            (            )            {            return            <h2>Whale<            /h2>            ;            }                  

Salvage and shut the file. In the side by side step, yous'll start connecting routes; for now, render the basic component in your application.

Open up App.js:

                      
  1. nano src/components/App/App.js

Add an <h1> tag with the proper noun of the website (Marine Mammals) inside of a <div> with a className of wrapper. This will serve as a template. The wrapper and <h1> tag will render on every folio. In full applications, you might add a navigation bar or a header component that you'd want on every folio.

Add the post-obit highlighted lines to the file:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            './App.css'            ;            function            App            (            )            {            render                          (                                      <div className=              "wrapper"              >                                      <h1>Marine Mammals<              /h1>                                      <              /div>                                      )                        ;            }            export            default            App;                  

Next, import Manatee and render inside the <div>. This volition serve as a placeholder until you add together more than routes:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            './App.css'            ;                          import              Manatee              from              '../Manatee/Manatee'              ;                        function            App            (            )            {            return            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>                          <Manatee              /              >                        <            /div>            )            ;            }            export            default            App;                  

Save and close the file.

Now that you take all of the components, add some padding to give the awarding a little space.

Open up App.css:

                      
  1. nano src/components/App/App.css

Then replace the contents with the following code that adds a padding of 20px to the .wrapper course:

router-tutorial/src/components/App/App.css

                      .wrapper            {            padding            :            20px;            }                  

Save and close the file. When y'all do, the browser will refresh to show your basic component:

Marine Mammals

At present you take a bones root component that yous will use to display other components. If you didn't have a router, y'all could conditionally brandish components using the useState Hook. But this wouldn't offer a great experience for your users. Anytime a user refreshes the page, the user'south selection would disappear. Further, they wouldn't be able to bookmark or share specific states of the application. A router will solve all these issues. The router volition preserve the user state and will requite the user a articulate URL that they tin can save or send to others.

In this step, you installed React Router and created basic components. The components are going to be individual pages that you'll display by road. In the next step, y'all'll add together routes and use the <Link> component to create performant hyperlinks.

Step 2 — Adding Routes

In this step, you'll create a base of operations router with private routes for each page. You'll order your routes to ensure that components are rendered correctly and you'll use the <Link> component to add together hyperlinks to your project that won't trigger a page refresh.

By the end of this pace, you'll take an application with a navigation that will display your components past route.

React Router is a declarative routing framework. That ways that you lot will configure the routes using standard React components. There are a few advantages to this arroyo. Offset, it follows the standard declaractive nature of React code. Y'all don't need to add a lot of code in componentDidMount methods or inside a useEffect Hook; your routes are components. Second, you lot can intuitively place routes inside of a component with other components serving as a template. As you read the code, you'll find exactly where the dynamic components will fit in relation to the global views such as navigation or footers.

To start adding routes, open up App.js:

                      
  1. nano src/components/App/App.js

The <h1> tag is going to serve as a global page title. Since you desire it to announced on every page, configure the router after the tag.

Import BrowserRouter, Route, and Switch from react-router-dom. BrowserRouter will exist the base configuration. Switch will wrap the dynamic routes and the Route component volition configure specific routes and wrap the component that should render:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;                          import              {              BrowserRouter,              Route,              Switch              }              from              'react-router-dom'              ;                        import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;            function            App            (            )            {            return            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>            <Manatee            /            >            <            /div>            )            ;            }            consign            default            App;                  

Add the BrowserRouter component to create a base of operations router. Anything exterior of this component will render on every page, so place information technology afterward your <h1> tag. In improver, if yous accept site-wide context that you want to use, or some other store such every bit Redux, place those components outside the router. This volition make them available to all components on any route:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            {            BrowserRouter,            Route,            Switch            }            from            'react-router-dom'            ;            import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;            role            App            (            )            {            return            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>                          <BrowserRouter>                        <Manatee            /            >                          <              /BrowserRouter>                        <            /div>            )            ;            }            export            default            App;                  

Next, add the Switch component within BrowserRouter. This component volition activate the correct route, much similar the JavaScript switch statement. Within of Switch, add together a Route component for each route. In this case, yous'll want the following routes: /manataee, /narwhal, and /whale. The Road component will accept a path as a parameter and surround a child component. The child component will brandish when the route is agile.

Create a route for the path / and render the Manatee component:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            {            BrowserRouter,            Route,            Switch            }            from            'react-router-dom'            ;            import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;            function            App            (            )            {            render            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>            <BrowserRouter>                          <Switch>                                      <Route path=              "/"              >                        <Manatee            /            >                          <              /Route>                                      <              /Switch>                        <            /BrowserRouter>            <            /div>            )            ;            }            consign            default            App;                  

Salve the file. When you do the browser will reload and you'll notice the information for the manatee component:

Manatee showing at route /

If you try a different route such equally http://localhost:3000/whale, you'll still discover the manatee component.

Manatee on /whale route

The Switch component will render the showtime route that matches that pattern. Any route will match /, so it will render on every folio. That also means that club is important. Since the router will exit as soon equally it finds a match, always put a more specific route before a less specific road. In other words, /whale would become before / and /whale/beluga would go earlier /whale.

If you want the road to lucifer only the route every bit written and not any child routes, y'all tin add the exact prop. For case, <Route verbal path="/manatee"> would match /manatee, simply not /manatee/african.

Update the route for the Manatee component to /manatee, so import the remaining components and create a route for each:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            {            BrowserRouter,            Route,            Switch            }            from            'react-router-dom'            ;            import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;                          import              Narwhal              from              '../Narwhal/Narwhal'              ;                                      import              Whale              from              '../Whale/Whale'              ;                        function            App            (            )            {            render            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>            <BrowserRouter>            <Switch>                          <Route path=              "/manatee"              >                                      <Manatee              /              >                                      <              /Route>                                      <Road path=              "/narwhal"              >                                      <Narwhal              /              >                                      <              /Route>                                      <Route path=              "/whale"              >                                      <Whale              /              >                                      <              /Road>                        <            /Switch>            <            /BrowserRouter>            <            /div>            )            ;            }            export            default            App;                  

Salve the file. When you exercise, the browser will refresh. If you lot visit http://localhost:3000/, but the <h1> tag will render, because no routes friction match whatever of the Route components:

No component on /

If you visit http://localhost:3000/whale, you'll find the Whale component:

Whale on /whale route

Now that you have some components, create navigation for a user to motion between pages.

Apply the <nav> element to denote that you are creating a navigation portion of the page. And then add an unordered list (<ul>) with a list item (<li>) and a hyperlink (<a>) for each mammal:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            {            BrowserRouter,            Route,            Switch            }            from            'react-router-dom'            ;            import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;            import            Narwhal            from            '../Narwhal/Narwhal'            ;            import            Whale            from            '../Whale/Whale'            ;            part            App            (            )            {            return            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>                          <nav>                                      <ul>                                      <li>              <a href=              "/manatee"              >Manatee<              /a>              <              /li>                                      <li>              <a href=              "/narwhal"              >Narwhal<              /a>              <              /li>                                      <li>              <a href=              "/whale"              >Whale<              /a>              <              /li>                                      <              /ul>                                      <              /nav>                        <BrowserRouter>            ...            <            /BrowserRouter>            <            /div>            )            ;            }            export            default            App;                  

Save the file. When you practise, the browser will refresh, just in that location will exist a problem. Since you are using the native browser links—<a> tags—you volition become the default browser behavior whatsoever time you click on a link. That means any time you click on a link, you'll trigger a full page refresh.

Notice that the network will reload all of the JavaScript files when you click a link. That'south a big performance price for your users.

Browser refresh on link click

At this signal, you could add a click event handler on each link and foreclose the default action. That would be a lot of piece of work. Instead, React Router has a special component chosen Link that will handle the work for you. It will create a link tag, simply preclude the default brower behavior while pushing the new location.

In App.js, import Link from react-router-dom. And so replace each <a> with a Link. You'll also need to change the href attribute to the to prop.

Finally, move the <nav> component inside of the BrowserRouter. This ensures that the Link component is controlled by react-router:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            {            BrowserRouter,            Link,                        Route,            Switch            }            from            'react-router-dom'            ;            import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;            import            Narwhal            from            '../Narwhal/Narwhal'            ;            import            Whale            from            '../Whale/Whale'            ;            function            App            (            )            {            return            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>                          <BrowserRouter>                        <nav>            <ul>            <li>                          <Link to=              "/manatee"              >Manatee<              /Link>                        <            /li>            <li>                          <Link to=              "/narwhal"              >Narwhal<              /Link>                        <            /li>            <li>                          <Link to=              "/whale"              >Whale<              /Link>                        <            /li>            <            /ul>            <            /nav>            <Switch>            <Route path=            "/manatee"            >            <Manatee            /            >            <            /Route>            <Road path=            "/narwhal"            >            <Narwhal            /            >            <            /Route>            <Road path=            "/whale"            >            <Whale            /            >            <            /Route>            <            /Switch>            <            /BrowserRouter>            <            /div>            )            ;            }            export            default            App;                  

Relieve the file. When you practice, the browser will refresh. When you click links, the page volition not refresh and the browser will non reload the JavaScript code:

No refresh on link click

In this step you added React Router to your current project. You lot created a road for each component and y'all added a navigation using the Link component to switch between routes without a page refresh.

In the side by side stride, you lot'll add more than circuitous routes that render dissimilar components using URL parameters.

Step iii — Accessing Route Data with Hooks

In this pace, yous'll use URL queries and parameters to create dynamic routes. You'll learn how to pull data from search parameters with the useLocation Hook and how to read data from dynamic URLs using the useParams Hook.

By the end of this step, you'll know how to access route data within of your components and how you can utilise that information to dynamically load components.

Suppose you wanted to add another level to your marine mammal application. In that location are many types of whales, and you could brandish information almost each one. You have two choices of how to attain this: You could employ the current route and add a specific whale type with search parameters, such as ?type=beluga. Y'all could also create a new road that includes the specific proper name afterwards the base URL, such as /whale/beluga. This tutorial will starting time with search parameters, since they are flexible and can handle multiple, different queries.

Offset, brand new components for different whale species.

Open up a new file Beluga.js in your text editor:

                      
  1. nano src/components/Whale/Beluga.js

Add an <h3> tag with the proper name Beluga:

router-tutorial/src/components/Whale/Beluga.js

                      import            React            from            'react'            ;            export            default            function            Beluga            (            )            {            return            (            <h3>Beluga<            /h3>            )            ;            }                  

Do the same thing for a blueish whale. Open a new file Blue.js in your text editor:

                      
  1. nano src/components/Whale/Blueish.js

Add an <h3> tag with the proper name Blue:

router-tutorial/src/components/Whale/Blue.js

                      import            React            from            'react'            ;            export            default            function            Blue            (            )            {            return            (            <h3>Blue<            /h3>            )            ;            }                  

Salvage and close the file.

Passing Additional Data with Search Parameters

Next, you are going to pass the whale data equally a search parameter. This will permit you pass information without needing to create a new URL.

Open up App.js so you can add together new links:

                      
  1. nano src/components/App/App.js

Add together two new links, one to /whale?type=beluga and i for /whale?type=blue:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            {            BrowserRouter,            Link,            Route,            Switch            }            from            'react-router-dom'            ;            import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;            import            Narwhal            from            '../Narwhal/Narwhal'            ;            import            Whale            from            '../Whale/Whale'            ;            function            App            (            )            {            return            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>            <BrowserRouter>            <nav>            <ul>            <li>            <Link to=            "/manatee"            >Manatee<            /Link>            <            /li>            <li>            <Link to=            "/narwhal"            >Narwhal<            /Link>            <            /li>            <li>            <Link to=            "/whale"            >Whale<            /Link>            <            /li>                          <li>              <Link to=              "/whale?type=beluga"              >Beluga Whale<              /Link>              <              /li>                                      <li>              <Link to=              "/whale?blazon=blue"              >Blue Whale<              /Link>              <              /li>                        <            /ul>            <            /nav>            <Switch>            ...            <            /Switch>            <            /BrowserRouter>            <            /div>            )            ;            }            export            default            App;                  

Save and close the file.

If you click on the links, you lot'll nevertheless encounter the regular whale folio. This shows that the standard route is still working correctly:

Beluga router with whale page

Since yous are correctly rendering the Whale component, you'll demand to update the component to pull the search query out of the URL and use it to render the correct child component.

Open Whale.js:

                      
  1. nano src/components/Whale/Whale.js

First, import the Beluga and Blueish components. Adjacent, import a Hook chosen useLocation from react-router-dom:

router-tutorial/src/components/Whale/Whale.js

                      import            React            from            'react'            ;                          import              {              useLocation              }              from              'react-router-dom'              ;                                      import              Beluga              from              './Beluga'              ;                                      import              Blue              from              './Blue'              ;                        consign            default            function            Whale            (            )            {            render            <h2>Whale<            /h2>            ;            }                  

The useLocation Claw pulls the location information from your page. This is not unique to React Router. The location object is a standard object on all browsers. If you open your browser console and type window.location, you'll get an object with information about your URL.

Window location in console

Notice that the location information includes search, but also includes other information, such as the pathname and the full href. The useLocation Hook volition provide this information for yous. Inside of Whale.js, telephone call the useLocation Hook. Destructure the result to pull out the search field. This will be a parameter string, such as ?type=beluga:

router-tutorial/src/components/Whale/Whale.js

                      import            React            from            'react'            ;            import            {            useLocation            }            from            'react-router-dom'            ;            import            Beluga            from            './Beluga'            ;            import            Blue            from            './Blue'            ;            consign            default            function            Whale            (            )            {            const            {            search            }            =            useLocation            (            )            ;            render            <h2>Whale<            /h2>            ;            }                  

There are a number of libraries, such every bit query-cord, that can parse the search for yous and convert it into an object that is easier to read and update. In this example, yous tin can use a regular expression to pull out the information near the whale blazon.

Use the .match method on the search string to pull out the blazon: search.friction match(/type=(.*)/). The parentheses inside the regular expression will capture the match into a results array. The kickoff item in the array is the full match: type=beluga. The second item is the data from the parentheses: beluga.

Utilise the data from the .match method to return the correct kid component:

router-tutorial/src/components/Whale/Whale.js

                      import            React            from            'react'            ;            import            {            useLocation            }            from            'react-router-dom'            ;            import            Beluga            from            './Beluga'            ;            import            Blue            from            './Blue'            ;            export            default            function            Whale            (            )            {            const            {            search            }            =            useLocation            (            )            ;                          const              match              =              search.              lucifer              (                              /                blazon=(.*)                /                            )              ;                                      const              type              =              lucifer?.              [              ane              ]              ;                                      return              (                                      <              >                                      <h2>Whale<              /h2>                                      {type              ===              'beluga'              &&              <Beluga              /              >              }                                      {type              ===              'blue'              &&              <Blue              /              >              }                                      <              /              >                                      )              ;                        }                  

The symbol ?. is chosen optional chaining. If the value exists, it returns the value. Otherwise, information technology volition return undefined. This will protect your component in instances where the search parameter is empty.

Save the file. When you practice, the browser will refresh and will render dissimilar whales:

Different whales with search params

Accessing URL Parameters

Search parameters work, merely they aren't the best solution in this case. Generally, yous'd employ search parameters to refine a page: toggling information or loading specific data. In this example, you lot are not refining a folio; you are creating a new static page. Fortunately, React Router provides a way to create dynamic URLs that preserve variable data called URL Parameters.

Open App.js:

                      
  1. nano src/components/App/App.js

Instead of passing the whale information as a search, you volition add it direct to the URL itself. That ways that y'all will move the seach into the URL instead of adding information technology after a ?. For instance, the query/whale?type=blueish will now exist /whale/blueish:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            {            BrowserRouter,            Link,            Route,            Switch            }            from            'react-router-dom'            ;            import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;            import            Narwhal            from            '../Narwhal/Narwhal'            ;            import            Whale            from            '../Whale/Whale'            ;            role            App            (            )            {            render            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>            <BrowserRouter>            <nav>            <ul>            <li>            <Link to=            "/manatee"            >Manatee<            /Link>            <            /li>            <li>            <Link to=            "/narwhal"            >Narwhal<            /Link>            <            /li>            <li>            <Link to=            "/whale"            >Whale<            /Link>            <            /li>            <li>            <Link to=                          "/whale/beluga"                        >Beluga Whale<            /Link>            <            /li>            <li>            <Link to=                          "/whale/blueish"                        >Blue Whale<            /Link>            <            /li>            <            /ul>            <            /nav>            <Switch>            <Route path=            "/manatee"            >            <Manatee            /            >            <            /Route>            <Route path=            "/narwhal"            >            <Narwhal            /            >            <            /Route>            <Route path=            "/whale"            >            <Whale            /            >            <            /Route>            <            /Switch>            <            /BrowserRouter>            <            /div>            )            ;            }            export            default            App;                  

Now you need to create a new route that can capture both /whale/beluga and /whale/blue. You could add them past hand, just this wouldn't piece of work in situations where you don't know all the possibilities alee of fourth dimension, such equally when you take a list of users or other dynamic data.

Instead of making a route for each one, add together a URL param to the electric current path. The URL param is a keyword prefaced with a colon. React Router will employ the parameter as a wildcard and will match whatsoever route that contains that pattern.

In this instance, create a keyword of :blazon. The full path will be /whale/:type. This will match any route that starts with /whale and it volition relieve the variable information inside a parameter variable chosen type. This route will non lucifer /whale, since that does not comprise an additional parameter.

Yous can either add /whale as a route after the new route or you can add together information technology earlier the route of /whale/:blazon with the exact keyword.

Add a new route of /whale/:type and add an exact property to the current route:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            {            BrowserRouter,            Link,            Route,            Switch            }            from            'react-router-dom'            ;            import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;            import            Narwhal            from            '../Narwhal/Narwhal'            ;            import            Whale            from            '../Whale/Whale'            ;            function            App            (            )            {            return            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>            <BrowserRouter>            <nav>            <ul>            <li>            <Link to=            "/manatee"            >Manatee<            /Link>            <            /li>            <li>            <Link to=            "/narwhal"            >Narwhal<            /Link>            <            /li>            <li>            <Link to=            "/whale"            >Whale<            /Link>            <            /li>            <li>            <Link to=            "/whale/beluga"            >Beluga Whale<            /Link>            <            /li>            <li>            <Link to=            "/whale/blue"            >Blue Whale<            /Link>            <            /li>            <            /ul>            <            /nav>            <Switch>            <Route path=            "/manatee"            >            <Manatee            /            >            <            /Route>            <Route path=            "/narwhal"            >            <Narwhal            /            >            <            /Road>            <Road            verbal            path=            "/whale"            >            <Whale            /            >            <            /Route>                          <Route path=              "/whale/:type"              >                                      <Whale              /              >                                      <              /Route>                        <            /Switch>            <            /BrowserRouter>            <            /div>            )            ;            }            export            default            App;                  

Save and shut the file. Now that you are passing new information, y'all need to access it and use the information to render dynamic components.

Open Whale.js:

                      
  1. nano src/components/Whale/Whale.js

Import the useParams Claw. This will connect to your router and pull out whatsoever URL parameters into an object. Destructure the object to pull out the type field. Remove the code for parsing the search and apply the parameter to conditionally render kid components:

router-tutorial/src/components/Whale/Whale.js

                      import            React            from            'react'            ;            import            {            useParams            }            from            'react-router-dom'            ;            import            Beluga            from            './Beluga'            ;            import            Blue            from            './Blue'            ;            export            default            function            Whale            (            )            {                          const              {              blazon              }              =              useParams              (              )              ;                        return            (            <            >            <h2>Whale<            /h2>            {type            ===            'beluga'            &&            <Beluga            /            >            }            {blazon            ===            'blue'            &&            <Bluish            /            >            }            <            /            >            )            ;            }                  

Salve and close the file. When you do, the browser will refresh and yous'll exist able to utilize the new URLs, such as http://localhost:3000/whale/beluga:

Beluga whale parameter

URL parameters are a articulate way to pass conditional data. They are not as flexible equally search parameters, which tin can exist combined or reordered, but they are more clear and easier for search engines to index.

In this pace yous passed variable data using search parameters and URL parameters. You too used the useLocation and useParams Hooks to pull data out and to return provisional components.

Simply there is one problem: The listing of routes is getting long and you are starting to get most duplicates with the /whale and /whale/:type routes. React Router lets you split up out child routes direct in the component, which means you don't demand to have the whole listing in a single component. In the next step, you lot'll render routes directly inside of child components.

Stride 4 — Nesting Routes

Routes can grow and go more complex. React Router uses nested routes to return more specific routing information inside of child components. In this step, you'll use nested routes and add routes in different components. Past the cease of this step, you'll have different options for rendering your data.

In the terminal pace, yous added routes inside of App.js. This has some advantages: It keeps all routes in one place, essentially creating a site map for your application. Only it can hands grow and be difficult to read and maintain. Nested routes group your routing information directly in the components that volition return other components, giving you the power to create mini-templates throughout your awarding.

Open App.js:

                      
  1. nano src/components/App/App.js

Remove the /whale/:type road and remove the verbal prop so you only accept a whale route:

router-tutorial/src/components/App/App.js

                      import            React            from            'react'            ;            import            {            BrowserRouter,            Link,            Route,            Switch            }            from            'react-router-dom'            ;            import            './App.css'            ;            import            Manatee            from            '../Manatee/Manatee'            ;            import            Narwhal            from            '../Narwhal/Narwhal'            ;            import            Whale            from            '../Whale/Whale'            ;            role            App            (            )            {            return            (            <div className=            "wrapper"            >            <h1>Marine Mammals<            /h1>            <BrowserRouter>            <nav>            <ul>            <li>            <Link to=            "/manatee"            >Manatee<            /Link>            <            /li>            <li>            <Link to=            "/narwhal"            >Narwhal<            /Link>            <            /li>            <li>            <Link to=            "/whale"            >Whale<            /Link>            <            /li>            <li>            <Link to=            "/whale/beluga"            >Beluga Whale<            /Link>            <            /li>            <li>            <Link to=            "/whale/blue"            >Blue Whale<            /Link>            <            /li>            <            /ul>            <            /nav>            <Switch>            <Road path=            "/manatee"            >            <Manatee            /            >            <            /Route>            <Road path=            "/narwhal"            >            <Narwhal            /            >            <            /Route>                          <Road path=              "/whale"              >                                      <Whale              /              >                                      <              /Route>                        <            /Switch>            <            /BrowserRouter>            <            /div>            )            ;            }            consign            default            App;                  

Save and close the file.

Side by side, open up Whale.js. This is where you volition add the nested road.

                      
  1. nano src/components/Whale/Whale.js

You will need to do two things. Start, get the electric current path with the useRouteMatch Hook. Next, return the new <Switch> and <Road> components to display the correct components.

Import useRouteMatch. This will render an object that contains the path and the url. Destructure the object to become the path. You'll use this as the basis for your new routes:

router-tutorial/src/components/Whale/Whale.js

                      import            React            from            'react'            ;            import            {            useRouteMatch            }            from            'react-router-dom'            ;            import            Beluga            from            './Beluga'            ;            import            Blue            from            './Bluish'            ;            export            default            office            Whale            (            )            {                          const              {              path              }              =              useRouteMatch              (              )              ;                        render            (            <            >            <h2>Whale<            /h2>            {type            ===            'beluga'            &&            <Beluga            /            >            }            {type            ===            'blueish'            &&            <Bluish            /            >            }            <            /            >            )            ;            }                  

Adjacent, import Switch and Route so you can add together in new routes. Your new routes will be the aforementioned every bit you fabricated in App.js, just you do not need to wrap them with BrowserRouter. Add the new routes, but prefix the route with the path. The new component will render exactly where you identify them, so add the new routes after the <h2>:

router-tutorial/src/components/Whale/Whale.js

                      import            React            from            'react'            ;            import            {            Switch,              Route,                        useRouteMatch            }            from            'react-router-dom'            ;            import            Beluga            from            './Beluga'            ;            import            Blue            from            './Blue'            ;            export            default            function            Whale            (            )            {            const            {            path            }            =            useRouteMatch            (            )            ;            return            (            <            >            <h2>Whale<            /h2>                          <Switch>                                      <Route path=              {                              `                                  ${path}                                /beluga                `                            }              >                                      <Beluga              /              >                                      <              /Road>                                      <Road path=              {                              `                                  ${path}                                /blueish                `                            }              >                                      <Blue              /              >                                      <              /Route>                                      <              /Switch>                        <            /            >            )            ;            }                  

Salvage the file. When you lot do, the browser will refresh and you'll be able to visit the child routes.

Visiting child routes

This is a little actress code, but information technology keeps the kid routes situated with their parent. Non all projects apply nested routes: some adopt having an explicit listing. Information technology is a matter of squad preference and consistency. Cull the pick that is best for your project, and you lot tin always refactor later on.

In this footstep, you lot added nested routes to your project. You pulled out the current path with the useRouteMatch Hook and added new routes in a component to render the new components inside of a base of operations component.

Determination

React Router is an important role of any React project. When you build single page applications, yous'll utilize routes to separate your application into usable pieces that users tin can access hands and consistently.

As yous start to separate your components into routes, yous'll be able to take advantage of code splitting, preserving state via query parameters, and other tools to improve the user feel.

If you would like to read more React tutorials, check out our React Topic page, or return to the How To Lawmaking in React.js serial page.

armstrongcasympere.blogspot.com

Source: https://www.digitalocean.com/community/tutorials/how-to-handle-routing-in-react-apps-with-react-router

Post a Comment for "React Router Route Causes Root App to Render Again"