Skip to content

Commit cd55a4b

Browse files
committed
Implement wrap-around functionality for sculpture gallery navigation
1 parent f3d9794 commit cd55a4b

1 file changed

Lines changed: 34 additions & 6 deletions

File tree

src/content/learn/state-a-components-memory.md

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -193,12 +193,20 @@ const [index, setIndex] = useState(0);
193193
This is how they work together in `handleClick`:
194194

195195
```js
196+
const hasNext = index < sculptureList.length - 1;
197+
196198
function handleClick() {
197-
setIndex(index + 1);
199+
if (hasNext) {
200+
setIndex(index + 1);
201+
} else {
202+
setIndex(0);
203+
}
198204
}
199205
```
200206

201-
Now clicking the "Next" button switches the current sculpture:
207+
The `hasNext` check circles back to the first sculpture after the last one.
208+
209+
Now clicking the "Next" button switches the current sculpture, wrapping around to the first one after the last:
202210

203211
<Sandpack>
204212

@@ -208,9 +216,14 @@ import { sculptureList } from './data.js';
208216

209217
export default function Gallery() {
210218
const [index, setIndex] = useState(0);
219+
const hasNext = index < sculptureList.length - 1;
211220

212221
function handleClick() {
213-
setIndex(index + 1);
222+
if (hasNext) {
223+
setIndex(index + 1);
224+
} else {
225+
setIndex(0);
226+
}
214227
}
215228

216229
let sculpture = sculptureList[index];
@@ -392,9 +405,14 @@ import { sculptureList } from './data.js';
392405
export default function Gallery() {
393406
const [index, setIndex] = useState(0);
394407
const [showMore, setShowMore] = useState(false);
408+
const hasNext = index < sculptureList.length - 1;
395409

396410
function handleNextClick() {
397-
setIndex(index + 1);
411+
if (hasNext) {
412+
setIndex(index + 1);
413+
} else {
414+
setIndex(0);
415+
}
398416
}
399417

400418
function handleMoreClick() {
@@ -573,9 +591,14 @@ function Gallery() {
573591
// Each useState() call will get the next pair.
574592
const [index, setIndex] = useState(0);
575593
const [showMore, setShowMore] = useState(false);
594+
const hasNext = index < sculptureList.length - 1;
576595

577596
function handleNextClick() {
578-
setIndex(index + 1);
597+
if (hasNext) {
598+
setIndex(index + 1);
599+
} else {
600+
setIndex(0);
601+
}
579602
}
580603

581604
function handleMoreClick() {
@@ -757,9 +780,14 @@ import { sculptureList } from './data.js';
757780
export default function Gallery() {
758781
const [index, setIndex] = useState(0);
759782
const [showMore, setShowMore] = useState(false);
783+
const hasNext = index < sculptureList.length - 1;
760784

761785
function handleNextClick() {
762-
setIndex(index + 1);
786+
if (hasNext) {
787+
setIndex(index + 1);
788+
} else {
789+
setIndex(0);
790+
}
763791
}
764792

765793
function handleMoreClick() {

0 commit comments

Comments
 (0)