Created
November 2, 2025 21:39
-
-
Save imjacobclark/0833517fcce0bd05e1549efcb3131c00 to your computer and use it in GitHub Desktop.
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 { useState, useEffect } from 'react'; | |
| const PageOne = () => <h1>Page One</h1> | |
| const PageTwo = () => <h1>Page Two</h1> | |
| export default function Home() { | |
| const [page, setPage] = useState(-1); | |
| const pages = [PageOne, PageTwo]; | |
| const Page = pages[page]; | |
| useEffect(() => { | |
| const currentHistoryState = window.history.state ?? {}; | |
| const onPopState = (event) => { | |
| setPage(event.state?.location); | |
| }; | |
| const newHistoryState = { | |
| ...currentHistoryState, | |
| location: -1 | |
| } | |
| window.history.pushState(newHistoryState, '', '/'); | |
| window.addEventListener('popstate', onPopState); | |
| return () => window.removeEventListener('popstate', onPopState); | |
| }, []) | |
| return ( | |
| <main> | |
| {page === -1 && <h1>Hello Next.js</h1>} | |
| {page !== -1 && pages[page] && <Page />} | |
| {page >= pages.length && <h1>The end.</h1>} | |
| <button | |
| onClick={() => { | |
| const next = page + 1; | |
| setPage(next); | |
| window.history.pushState( | |
| { ...(window.history.state ?? {}), location: next }, | |
| '', | |
| '/' | |
| ); | |
| }} | |
| > | |
| Next Page | |
| </button> | |
| </main> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment