Created
August 16, 2021 23:23
-
-
Save dhruvilp/9bb5f2fda07b8b946a4323f7a067038e to your computer and use it in GitHub Desktop.
React useHistory hook 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 from "react"; | |
import { BrowserRouter as Router, | |
Switch, Route, Link, useHistory} from "react-router-dom"; | |
export default function BasicExample() { | |
return ( | |
<Router> | |
<div> | |
<Switch> | |
<Route exact path="/"> | |
<Home /> | |
</Route> | |
<Route path="/about"> | |
<About /> | |
</Route> | |
<Route path="/dashboard"> | |
<Dashboard /> | |
</Route> | |
</Switch> | |
</div> | |
</Router> | |
); | |
} | |
function Home() { | |
let history = useHistory(); | |
const handleClick1 = () => history.push("/about"); | |
const handleClick2 = () => history.push("/dashboard"); | |
return ( | |
<div> | |
<h2>Home</h2> | |
<button type="button" onClick={handleClick1}> | |
Go About | |
</button> | |
<span style={{paddingLeft: '5px'}}> | |
<button type="button" onClick={handleClick2}> | |
Go Dashboard | |
</button> | |
</span> | |
</div> | |
); | |
} | |
function About() { | |
let history = useHistory(); | |
const handleClick = () => history.push("/"); | |
return ( | |
<div> | |
<h2>About</h2> | |
<button type="button" onClick={handleClick}> | |
Go Home | |
</button> | |
</div> | |
); | |
} | |
function Dashboard() { | |
let history = useHistory(); | |
const handleClick = () => history.push("/"); | |
return ( | |
<div> | |
<h2>Dashboard</h2> | |
<button type="button" onClick={handleClick}> | |
Go Home | |
</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment