When I try loading useBlocker inside a class based component It throws the following error Error: useBlocker must be used within a data router. S to fix this, we have to replace BrowserRouter with createBrowserRouter. How do I replace with the following structure when class based component are involved. I have added withRouter
custom HOC to support router v6
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import { Provider as ReduxProvider } from "react-redux";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ReduxProvider store={store}>
<App />
</ReduxProvider>
</React.StrictMode>
);
import {
Location,
NavigateFunction,
Params,
useLocation,
useNavigate,
useParams,
} from "react-router-dom";
export interface RouterProps {
location: Location;
navigate: NavigateFunction;
params: Params;
}
export interface WithRouter {
router: RouterProps;
}
function withRouter(Component: any) {
function ComponentWithRouterProp(props: any) {
const location = useLocation();
const navigate = useNavigate();
const params = useParams();
return <Component {...props} router={{ location, navigate, params }} />;
}
return ComponentWithRouterProp;
}
export default withRouter;
class App extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props);
}
render() {
return (
<div className='container'>
<Navbar />
<Suspense>
<Routes>
<Route path="/" element={ <Home /> } />
<Route path="/team" element={ <Team /> } />
<Route path="/about" element={ <About /> } />
</Routes>
</Suspense>
</div>
);
}
}
export default withRouter(App);
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useBlocker } from "react-router";
import Dialog from "../Dialog";
const RouterPrompt = (props) => {
const { when } = props;
const [showPrompt, setShowPrompt] = useState<boolean>(false);
const blocker = useBlocker((props): any => {
const { pathname } = props.nextLocation;
if (when && pathname !== "/login") {
setShowPrompt(true);
return true;
}
return false;
});
const handleOK = () => {
(() => {
blocker.proceed();
})();
};
const handleCancel = () => {
blocker.reset();
};
return (
<Dialog
onSuccess={handleOK}
onCancel={handleCancel}
/>
);
};