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
CodePudding user response:
const handleVisibleArray = () => {
setvisibleArray(prevState => {
return ((prevState 3) <= totalArrayLength ? (visibleArray 3) : 0);
});
};
CodePudding user response:
You could use the modulus operator to determine how many indexes are left and then use Math.min
... Math.min(3, (totalArrayLength % (visibleArray 3))) ...
const handleVisibleArray = () => {
const counter = visibleArray <= totalArrayLength ? visibleArray Math.min(3, (totalArrayLength % (visibleArray 3))) : 0;
setvisibleArray(counter);
};
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Try to Initialize a variable increment
as 3 and for each time you click, increment the variable increment
by 3.
const [increment, setIncrement] = useState(3);
const handleVisibleArray = () => {
const counter = visibleArray <= totalArrayLength ? visibleArray increment : 0;
setIncrement(increment 3);
setvisibleArray(counter);
};
EDIT: If you are not looking to keep track of the increment and/or don't intend to use it in the rest of your component, I'd go with @Kinglish's answer