Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 34 additions & 6 deletions src/content/learn/state-a-components-memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,12 +193,20 @@ const [index, setIndex] = useState(0);
This is how they work together in `handleClick`:

```js
const hasNext = index < sculptureList.length - 1;

function handleClick() {
setIndex(index + 1);
if (hasNext) {
setIndex(index + 1);
} else {
setIndex(0);
}
}
```

Now clicking the "Next" button switches the current sculpture:
The `hasNext` check circles back to the first sculpture after the last one.

Now clicking the "Next" button switches the current sculpture, wrapping around to the first one after the last:

<Sandpack>

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

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

function handleClick() {
setIndex(index + 1);
if (hasNext) {
setIndex(index + 1);
} else {
setIndex(0);
}
}

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

function handleNextClick() {
setIndex(index + 1);
if (hasNext) {
setIndex(index + 1);
} else {
setIndex(0);
}
}

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

function handleNextClick() {
setIndex(index + 1);
if (hasNext) {
setIndex(index + 1);
} else {
setIndex(0);
}
}

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

function handleNextClick() {
setIndex(index + 1);
if (hasNext) {
setIndex(index + 1);
} else {
setIndex(0);
}
}

function handleMoreClick() {
Expand Down
Loading