Below solution will ensure that the URL changes when arrayIndex is updated, reflecting the current path

Key points:

  • useEffect triggers navigation to the new path whenever arrayIndex changes.
  • handleNext and handlePrev update arrayIndex accordingly.
  • navigate is used to programmatically change the route.

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;

Explanation

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:

  • Prevents the default link behavior.
  • Sets the loading state to true to show the loading message.
  • Preloads the Page component using await import(“./Page”).
  • Resets the loading state to false.
  • Uses history.push(“/page”) to navigate to the new page.

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.

Support On Demand!

ReactJS