Reputation: 13
import React, { useState } from "react";
import { render } from "react-dom";
const Parent = (props) => {
let [id, setId] = useState(1);
return (
<div>
<button
onClick={() => {
setId(++id % 4);
}}
>
Increment
</button>
{id === 1 && <h2>Image 1</h2>}
{id === 2 && <h2>Image 2</h2>}
{id === 3 && <h2>Image 3</h2>}
{id === 0 && <h2>Image 4</h2>}
{id}
<button
onClick={() => {
setId(Math.abs(--id) % 4);
}}
>
Decrement
</button>
</div>
);
};
Upvotes: 1
Views: 51
Reputation: 25416
Initially the id
is set to 1
and when you click decrement
then it will become 0
, so far so good.
But as soon as you hit decrement
again then it will be -1
but you have used Math.abs
so it will make it to 1
and this goes on and on
You can just change the login a bit as:
onClick={() => {
const newId = --id;
setId(newId < 0 ? 3 : newId);
}}
You can also use below logic as:
setId((--id + 4) % 4);
Upvotes: 1