skip to Main Content

On our project, we were using version 4 of react-router, and we have migrated to version 6.

However, we are encountering an issue that I cannot identify since the change from the useLocation API to useNavigate.

Here’s my function:

import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';

import { IProps, IPropsReturn } from './types';

export const useSteppers = ({ steppers, redirectPath }: IProps): IPropsReturn => {
  const { customerOuid, routeFeature, routeTab, step } = useParams();
  const navigate = useNavigate();
  const currentStep = step ? parseInt(step) : 0;

  useEffect(() => {
    if (!step || currentStep > steppers.length - 1) {
      navigate(`/customer/${customerOuid}/${routeTab}/${routeFeature}/0`);
    }
  }, [step]);

  const handlePrevStep = () => {
    const prevStep = currentStep - 1;

    if (currentStep === 0) {
      return navigate(-1);
    }
    return navigate(`${prevStep}`, { replace: true });
  };

  const handleSubmit = (triggerPolling: () => void) => {
    const nextStep = currentStep + 1;

    if (currentStep === steppers.length - 1 && redirectPath) {
      if (triggerPolling) {
        return triggerPolling();
      }
      return navigate(redirectPath, { replace: true });
    }

    return navigate(`${nextStep}`, { replace: true });
  };

  return {
    currentStep,
    handlePrevStep,
    handleSubmit,
  };
};

The problem is actually here :

return navigate(`${nextStep}`, { replace: true });

When the function is executed, the navigate function returns a route :

localhost:3000/#/customer/123/accounting/chargeCancellation/0/1

Do you see the problem ? 0/1 I would like only /1

Before we migrate to v6 we use :

    const history = useHistory(); 
    return history.replace(`${nextStep}`);

2

Answers


  1. According with react-router-dom doc here you can simply add ../ before your desired path. It will be replace in the route history, so going back will intercept the parent route, depending on how you configured your routes.

    In your case try using

    return navigate(`../${nextStep}`, {replace:true});

    I hope it could help you

    Login or Signup to reply.
  2. You could simply use a relative path to navigate to a sibling route:

    navigate(`../${prevStep}`, { replace: true });
    
    navigate(`../${nextvStep}`, { replace: true });
    

    You could also compute the absolute path as well:

    navigate(
      `/customer/${customerOuid}/${routeTab}/${routeFeature}/${prevStep}`,
      { replace: true }
    );
    
    navigate(
      `/customer/${customerOuid}/${routeTab}/${routeFeature}/${nextStep}`,
      { replace: true }
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search