skip to Main Content

I am using React router dom v6, and the "useHistory" method is not available in the React router v6 version.

Please suggest me how I can implment below code with React Router com v6 version

history.listen(onParentNavigate);

export default () => {
    const ref = useRef(null);
    const location = useLocation();
    const navigate = useNavigate();
 
    const history = useHistory();
 
    useEffect(() => {
        const { onParentNavigate } = mount(ref.current, {
            onNavigate: ({ location }: any) => {
                navigate(location.pathname);
            },
        });
 
        // PLEASE SUGGEST ME HOW I CAN IMPLEMENT THIS WITH REACT ROUTER V6 VERSION
        history.listen(onParentNavigate);
 
    }, []);
 
    return (
        <div ref={ref} />
 
    )
}

2

Answers


  1. I think you can refer to this post. It seems that you need to use useNavigate instead of useHistory

    Login or Signup to reply.
  2. Issue

    React-Router-DOM 6 doesn’t export any useHistory hook nor surface the history object.

    Solution

    Data Router

    If you are using a Data Router (see Picking a Router) you can subscribe to the router.

    Example:

    import { createBrowserRouter } from 'react-router-dom';
    
    export const router = createBrowserRouter([
      // ... your routes configuration
    ]);
    
    import { router } from '../path/to/router';
    
    export default () => {
      const ref = useRef(null);
    
      const navigate = useNavigate();
     
      useEffect(() => {
        const { onParentNavigate } = mount(ref.current, {
          onNavigate: ({ location }: any) => {
            navigate(location.pathname);
          },
        });
     
        router.subscribe(onParentNavigate);
      }, []);
     
      return <div ref={ref} />;
    };
    

    Regular Non-Data Router

    If you are not using any Data Router then you’ll need to use the HistoryRouter and a custom history object.

    Example:

    import { createBrowserHistory } from "history";
    
    export const history = createBrowserHistory({ window });
    
    import { unstable_HistoryRouter as HistoryRouter } from "react-router-dom";
    import { history } from "../path/to/history";
    
    ReactDOM.render(
      <HistoryRouter history={history}>
        {/* The rest of your app goes here */}
      </HistoryRouter>,
      root
    );
    
    import { history } from "../path/to/history";
    
    export default () => {
      const ref = useRef(null);
    
      const navigate = useNavigate();
     
      useEffect(() => {
        const { onParentNavigate } = mount(ref.current, {
          onNavigate: ({ location }: any) => {
            navigate(location.pathname);
          },
        });
     
        history.listen(onParentNavigate);
      }, []);
     
      return <div ref={ref} />;
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search