When clicked on button increase value by 3 and when reached array length reset it to 0

Issue

  const handleVisibleArray = () => {
   const counter = visibleArray <= totalArrayLength ? visibleArray + 3 : 0;
   setvisibleArray(counter);
 };

My values go more than the total array length.
If the array length is 11, then on every click it should increase by.

  • first, click 3
  • second click 6
  • third click 9
  • fourth click 2 and in next click it should make it to 0

Solution

const handleVisibleArray = () => {
  setvisibleArray(prevState => {
    return ((prevState + 3) <= totalArrayLength ? (visibleArray + 3) : 0);
  });
};

Answered By – davood Sandoghsaz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published