Official Solution
import React, { useReducer } from 'react';
function clamp(n, min, max) {
return Math.max(min, Math.min(max, n));
}
function reducer(state, action) {
switch (action.type) {
case 'next':
return { ...state, page: clamp(state.page + 1, 1, state.totalPages) };
case 'prev':
return { ...state, page: clamp(state.page - 1, 1, state.totalPages) };
case 'setSize':
return { ...state, pageSize: action.value, page: 1 };
default:
return state;
}
}
export default function App() {
const [state, dispatch] = useReducer(reducer, { page: 1, pageSize: 10, totalPages: 7 });
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode pages</h2>
<div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
<button type='button' onClick={() => dispatch({ type: 'prev' })} disabled={state.page === 1} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Prev</button>
<div style={{ color: '#555' }}>Page {state.page} / {state.totalPages}</div>
<button type='button' onClick={() => dispatch({ type: 'next' })} disabled={state.page === state.totalPages} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Next</button>
</div>
<div style={{ marginTop: 12 }}>
<label>
Page size{' '}
<select value={state.pageSize} onChange={(e) => dispatch({ type: 'setSize', value: Number(e.target.value) })} style={{ padding: '8px 10px', borderRadius: 12, border: '1px solid #bbb' }}>
<option value={5}>5</option>
<option value={10}>10</option>
<option value={20}>20</option>
</select>
</label>
</div>
</div>
);
}
No comments yet. Start the discussion!