With react-router I can use the Link element to create links which are natively handled by react router.
I see internally it calls t
So in my answer there are 3 different ways to redirect programmatically to a route. Some of the solutions has been presented already but the following ones focused only for functional components with an additional demo application.
Using the following versions:
react: 16.13.1
react-dom: 16.13.1
react-router: 5.2.0
react-router-dom: 5.2.0
typescript: 3.7.2
Configuration:
So first of all the solution is using HashRouter, configured as follows:
// ... buttons for redirect
From the documentation about :
A
that uses the hash portion of the URL (i.e.window.location.hash) to keep your UI in sync with the URL.
Solutions:
to push using useState:Using in a functional component (RedirectPushAction component from my repository) we can use useState to handle redirect. Tricky part is once the redirection happened we need to set the redirect state back to false. By using setTimeOut with 0 delay we are waiting until React commits Redirect to the DOM then getting back the button in order to use next time.
Please find my example below:
const [redirect, setRedirect] = useState(false);
const handleRedirect = useCallback(() => {
let render = null;
if (redirect) {
render =
// in order wait until commiting to the DOM
// and get back the button for clicking next time
setTimeout(() => setRedirect(false), 0);
}
return render;
}, [redirect]);
return <>
{handleRedirect()}
>
From
Rendering a
will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
useHistory hook:In my solution there is a component called UseHistoryAction which represents the following:
let history = useHistory();
return
The
useHistoryhook gives us access to the history object which helps us programmatically navigate or change routes.
withRouter, get the history from props:Created one component called WithRouterAction, displays as below:
const WithRouterAction = (props:any) => {
const { history } = props;
return
}
export default withRouter(WithRouterAction);
Reading from withRouter documentation:
You can get access to the
historyobject's properties and the closest's match via thewithRouterhigher-order component.withRouterwill pass updatedmatch,location, andhistoryprops to the wrapped component whenever it renders.
Demo:
For better representation I have built a GitHub repository with these examples, please find it below:
https://github.com/norbitrial/react-router-programmatically-redirect-examples
I hope this helps!