Skip to content

Instantly share code, notes, and snippets.

@debanshu
Created November 23, 2020 22:22
Show Gist options
  • Select an option

  • Save debanshu/052ef9f204bc664e1c312fe9b31a240b to your computer and use it in GitHub Desktop.

Select an option

Save debanshu/052ef9f204bc664e1c312fe9b31a240b to your computer and use it in GitHub Desktop.
React Router Example
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