I am trying to implement pagination for components named "Shop", Contact and Cart 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 to 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" the next component is displayed. After that if we again click the "Prev" then the previous component is displayed.
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
2
Answers
Your component will get reload when a link is clicked, so your state is not even saved.
This is caused as the component is first loaded and then the link is updated after the handleNext and handlePrev functions are called. To avoid this, we can keep track of the next and prev link at any point of time with the help of variables nextPath and prevPath. These keep the links for the next and prev pages and append it to the link call when the Next and Previous are clicked.
Also there is some improvement in the check for array index to make sure it doesn’t go out of bound.
Here’s the code :