Created
March 31, 2024 12:13
-
-
Save XXXMrG/0d0028fb12aff3c425175e0e93ac62e7 to your computer and use it in GitHub Desktop.
A small react router
This file contains 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 { useCallback, useEffect, useState } from 'react' | |
import './App.css' | |
function One() { | |
return <div>one</div> | |
} | |
function Two() { | |
return <div>two</div> | |
} | |
function App() { | |
const [state, setState] = useState('') | |
const handleGoOne = useCallback(() => { | |
window.history.pushState({ | |
path: '/one' | |
}, '', '/one') | |
setState('/one') | |
}, []); | |
const handleGoTwo = useCallback(() => { | |
window.history.pushState({ | |
path: '/two' | |
}, '', '/two') | |
setState('/two') | |
}, []); | |
const handlePop = useCallback((e) => { | |
console.log(e) | |
// if not set state, only the path change, but the view will not change | |
setState(e.state && e.state.path) | |
}, []) | |
useEffect(() => { | |
window.addEventListener('popstate', handlePop) | |
return () => { | |
window.removeEventListener('popstate', handlePop) | |
} | |
}, [handlePop]) | |
return ( | |
<> | |
<div> | |
<button onClick={handleGoOne}>go one</button> | |
<button onClick={handleGoTwo}>go two</button> | |
</div> | |
{state === '/one' && <One />} | |
{state === '/two' && <Two />} | |
</> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment