Below solution will ensure that the URL changes when arrayIndex is updated, reflecting the current path
This should solve the issue and provide smooth navigation between the paths.
import { useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
const Bottombar = () => {
const pathArray = ["shop", "contact", "cart"];
const [arrayIndex, setArrayIndex] = useState(0);
const navigate = useNavigate();
useEffect(() => {
navigate(`/${pathArray[arrayIndex]}`);
}, [arrayIndex]);
const handleNext = () => {
if (arrayIndex === pathArray.length - 1) {
setArrayIndex(0);
} else {
setArrayIndex((prev) => prev + 1);
}
};
const handlePrev = () => {
if (arrayIndex === 0) {
setArrayIndex(pathArray.length - 1);
} else {
setArrayIndex((prev) => prev - 1);
}
};
return (
<div className="bottombar">
<div className="links">
<button onClick={handlePrev}>Previous</button>
<button onClick={handleNext}>Next</button>
</div>
</div>
);
};
export default Bottombar;
1. State and Navigation: In the Home component, we define a state variable loading to track whether the new page is being preloaded. The useHistory hook allows us to navigate programmatically.
2. Preloading and Navigation: When the user clicks the link, the navigateToPage function is triggered. This function:
3. Rendering: The App component sets up the routes using React Router. The home route renders the Home component. The /page route uses React.Suspense with a null fallback, ensuring that the loading state is managed within the Home component rather than showing a separate loading message.
This approach keeps the current page visible with a loading message until the new page is fully loaded, enhancing the user experience by providing a smooth transition between pages.
Work with our skilled React developers to accelerate your project and boost its performance.
Hire Reactjs Developers