Creating a component containing routes

We are going to define all of the routes to the pages we created by carrying out the following steps:

  1. Open App.tsx and add the following import statements:
import { BrowserRouter, Route } from 'react-router-dom';
import { AskPage } from './AskPage';
import { SearchPage } from './SearchPage';
import { SignInPage } from './SignInPage';
  1. In the App component's JSX, add BrowserRouter as the outermost element:
<BrowserRouter>
<div css={ ... } >
<Header />
<HomePage />
</div>
</BrowserRouter>

The BrowserRouter component will look for Route components nested within it and render the component defined if the route matches the location in the browser.

  1. Let's define some Route components in the JSX by replacing the previous reference to HomePage:
<BrowserRouter>
<div css={ ... } >
<Header />
<Route path="/" component={HomePage} />
<Route path="/search" component={SearchPage} />
<Route path="/ask" component={AskPage} />
<Route path="/signin" component={SignInPage} />
</div>
</BrowserRouter>
  1. Run the app by entering the npm start command in the Visual Studio Code Terminal. We'll see that the home page renders just like it did before, which is great.
  2. Now, enter /search at the end of the browser location path:

Here, we can see that the HomePage component has rendered, as well as the SearchPage component. Why has this happened? Well, BrowserRouter has matched the browser location path to /, as well as /search rendering both the HomePage and SearchPage components.

By default, BrowserRouter does the partial matching to the browser location path and will match and render all the Route components it can find.
  1. So, how do we resolve this problem? Well, we can tell the Route component that renders the HomePage component to do an exact match on the location in the browser:
<Route exact path="/" component={HomePage} />

Here, we use the exact Boolean attribute on the Route component to only render the specified component when there is an exact match on the path. 

Unlike other attributes, you don't need to specify the value of a Boolean attribute on an HTML element. Its presence on an element automatically means the value is true and its absence means the value is false.
  1. If we look at the running app, we'll see that the search results page renders as we expect:

Feel free to visit the other pages as well – they will render fine now. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.112.210