Created
November 23, 2020 22:22
-
-
Save debanshu/052ef9f204bc664e1c312fe9b31a240b to your computer and use it in GitHub Desktop.
React Router Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component, useState } from "react"; | |
| import { | |
| useLocation, | |
| BrowserRouter, | |
| Switch, | |
| Route, | |
| Link, | |
| } from "react-router-dom"; | |
| import "../styles/App.css"; | |
| class App extends Component { | |
| render() { | |
| return ( | |
| <div id="main"> | |
| {/* Do not remove the main div */} | |
| <BrowserRouter> | |
| <Switch> | |
| <Route exact path="/about"> | |
| <> | |
| <LocationDisplay /> | |
| <Link to="/">Home</Link> | |
| <Link to="/about">About</Link> | |
| <div>You are on the about page</div> | |
| </> | |
| </Route> | |
| <Route exact path="/"> | |
| <> | |
| <LocationDisplay /> | |
| <Link to="/">Home</Link> | |
| <Link to="/about">About</Link> | |
| <Home /> | |
| </> | |
| </Route> | |
| <Route path="*"> | |
| <div>No match</div> | |
| </Route> | |
| </Switch> | |
| </BrowserRouter> | |
| </div> | |
| ); | |
| } | |
| } | |
| function Home() { | |
| return <div>You are home.</div>; | |
| } | |
| export function LocationDisplay() { | |
| const { pathname } = useLocation(); | |
| return <div data-testid="location-display">{pathname}</div>; | |
| } | |
| export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment