Skip to content

Instantly share code, notes, and snippets.

@XXXMrG
Created March 31, 2024 12:13
Show Gist options
  • Save XXXMrG/0d0028fb12aff3c425175e0e93ac62e7 to your computer and use it in GitHub Desktop.
Save XXXMrG/0d0028fb12aff3c425175e0e93ac62e7 to your computer and use it in GitHub Desktop.
A small react router
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