Home > Net >  Can someone suggest the optimised way to do the below?
Can someone suggest the optimised way to do the below?

Time:10-05

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>
      );
    };
  • my decrement is not working fine can someone check this I am trying to select the images based on button click of user increment is working fine but decrement is not working here Can someone help me here *

CodePudding user response:

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:

CODESANDBOX LINK

onClick={() => {
  const newId = --id;
  setId(newId < 0 ? 3 : newId);
}}

You can also use below logic as:

setId((--id   4) % 4);
  • Related