how to listen page url change without page refresh in react?

Viewed 209

I do have some breadcrumbs on the page. When I do replaceState I see that url change there is no problem with that but I couldn't catch that url change in react component I've tried but no sense it works only once when component mounted.

const usePath = () => {
    const [path, pathSet] = useState(window.location.pathname);
    const listenToPopstate = () => {
        const winPath = window.location.pathname;
        pathSet(winPath);
    };
    useEffect(() => {
        window.addEventListener("locationchange", listenToPopstate);
        return () => {
            window.removeEventListener("locationchange", listenToPopstate);
        };
    }, []);
    return path;
};


const Breadcrumb = () => {

    const [state, stateSet] = useState(false);

    const path = usePath();

    useEffect(() => {
        path.indexOf('StoreSelection') > -1 && stateSet(true)
    }, [path]);

    return (
            <ol className="breadcrumb" style={breadcrumb}>
                <li key="1" className="breadcrumb-item align-items-center">
                    {state ? 'AAA' : 'BBB'}
                </li>
            </ol>
    );
}
1 Answers

I think you'll find instantiating a history object and using it to listen will be easier for you.

history

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

const usePath = () => {
  const [path, pathSet] = useState(history.location.pathname);

  const listener = (location, action) => {
    pathSet(location.pathname);
  };

  useEffect(() => {
    const unlisten = history.listen(listener);
    return unlisten;
  }, []);

  return path;
};
Related