I am trying to do pagination for components named “”, and using react-router-dom.
To store the URL paths I have used an array.
A state variable is used as an array index to retrive specific paths.
useRef is used to store specific path and change it whenever “next” or “prev” button is clicked.
Here whenever the Next or Prev is clicked, the components are displayed first and then the state variable is updated.
Thus when we click “Prev” after clicking “Next” we still go to next component. After that if we again click the “Prev” then we go the previous component.
Please provide a solution or an alternative way to implement the same.
import { Link } from "react-router-dom";
import { useRef, useState } from "react";
import "./bottombar.css";
const Bottombar = () => {
const pathArray = ["shop","contact","cart"]
const [array_index, setArrayIndex] = useState(0);
const path = useRef("");
const handleNext =() =>{
if(array_index== pathArray.length-1)
{
setArrayIndex(0)
}
else{
setArrayIndex(prev => prev+1)
}
}
const handlePrev =() =>{
if(array_index== 0)
{
setArrayIndex(pathArray.length-1)
}
else{
setArrayIndex(prev => prev-1)
}
}
path.current= pathArray[array_index];
return (
<div className="bottombar">
<div className="links">
<Link to={"/"+path.current} onClick={handlePrev}>Previous</Link>
<Link to={"/"+path.current} onClick={handleNext}>Next</Link>
</div>
</div>
);
};
export default Bottombar