I am having a react component with a button in it. On click on it, I make an API to get the link from the backend. And then navigate to that page whose route is already defined in the routing config.
Consider the link I am getting from the backend is /dummy
, though its present in the routing config, the URL changes with the new route but the component is not getting rendered. Routes are defined using Outlet component, and there is a wrapper component for each route that will determine if that route can be visited.
Component code
import { useNavigate } from "react-router-dom";
import { batch, useSelector, useDispatch } from "react-redux";
const Dummy = () => {
const navigate = useNavigate();
const dispatch = useDispatch();
const handleClick = async() => {
dispatch(setLoading(true));
const link = await getLink(); // here API is being made for the link whose route is present in the router
if (link === "/") {
navigate("", { replace: true });
} else {
navigate(`/${link}`, { replace: true });
}
dispatch(setLoading(false));
}
return(
<button onClick={handleClick}>Get Link</button>
)
}
App
class App extends React.Component<WithRouterProps, {}> {
render(){
return (
<div>
<Suspense fallback={<Loader/>}>
<Outlet />
</Suspense>
</div>
)
}
}
export default withRouter(App);
index
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}>
<AppRouter />
</ReduxProvider>
</React.StrictMode>
);
AppRouter
const AppRouter: FC = () => {
const router = createBrowserRouter(
createRoutesFromElements(
<Route element={<App />}>
<Route
path="/dummy"
element={<RouteWrapper path="/dummy" component={Dummy} />}
/>
</Route>
));
return <RouterProvider router={router} />;
}
RouteWrapper
const RouteWrapper = (props) => {
const {
loading, valid
} = useSelector((state) => state.baseReducer);
const getComponent = (props) => {
if (loading) {
return <Loader spinnerFlag={true} />;
} else if (valid) {
return <C {...props} {...cProps} />;
}
};
return <div>{getComponent(props)}</div>
}