Official Solution
import React, { useEffect, useState } from 'react';
function readPage() {
try {
const params = new URLSearchParams(window.location.search);
const n = Number(params.get('page') || '1');
if (Number.isNaN(n)) return 1;
return Math.min(20, Math.max(1, n));
} catch {
return 1;
}
}
export default function App() {
const [page, setPage] = useState(() => readPage());
useEffect(() => {
try {
const url = new URL(window.location.href);
url.searchParams.set('page', String(page));
window.history.replaceState({}, '', url.toString());
} catch {}
}, [page]);
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode pagination</h2>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<button type='button' disabled={page === 1} onClick={() => setPage((p) => Math.max(1, p - 1))} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff', opacity: page === 1 ? 0.6 : 1 }}>Prev</button>
<strong>Page {page}</strong>
<button type='button' disabled={page === 20} onClick={() => setPage((p) => Math.min(20, p + 1))} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff', opacity: page === 20 ? 0.6 : 1 }}>Next</button>
</div>
<p style={{ marginTop: 12, color: '#555' }}>URL stays in sync: ?page={page}</p>
</div>
);
}
No comments yet. Start the discussion!