in my React app I have 3 pages say a, b, c.
- I navigate from 'a' - 'b' - c(on form submits goes to) - 'b'.
- Now I am on page 'b' and click browser back.
- I am taken to page 'c' where I check a condition and if it fails I should be taken back to page 'b' and further pressing of back button to page 'a' as it was previous page to page 'b' as per app flow.
- User should not be allowed to visit page 'c' again.
- I have tried to do this with history.replace but its not replacing page 'c' entry from history stack and user keeps on navigating between page b and page c.
Please share any insights...
CodePudding user response:
maybe you could do something like this
first you need to create custom route that validate your condition if blabla cannot visit page 'c';
import { Redirect, Route, RouteProps } from 'react-router';
const ValidateRoute = (props) => {
const { component, children, ...rest } = props;
return (
<Route
{...rest}
render={(routeProps) =>
<place your condition here> ? (
Component ? (
<Component {...routeProps} />
) : (
children
)
) : (
<Redirect
to={{
pathname: '/',
}}
/>
)
}
/>
);
};
export default ValidateRoute;
then wrap your C route with ValidateRoute
<ValidateRoute component={c component} path="c path"/>
CodePudding user response:
You can use useHistory .replace hook to redirect your user to an specific page if that is your case OR you can set a Guard for your routes "which I personally prefer this approach" .
I wanted to provide you a code sample but found a good example on the following website so just visit it. https://blog.netcetera.com/how-to-create-guarded-routes-for-your-react-app-d2fe7c7b6122