Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Created July 8, 2021 09:39
Show Gist options
  • Save tjinlag/4dd09344b718ad29d7bf75f558cdc995 to your computer and use it in GitHub Desktop.
Save tjinlag/4dd09344b718ad29d7bf75f558cdc995 to your computer and use it in GitHub Desktop.
custom hook to navigate to another url in React App
const isFullUrl = (url = "") => url.match(/^\w+:\/\//);
const useNavigate = () => {
const history = useHistory();
const navigateTo = (url: string, { replace = false } = {} ) => {
if (isFullUrl(url)) {
window.location.href = url;
return;
}
if (replace) {
history.replace(url);
return;
}
history.push(url);
}
const navigateBack = (index: number = 1) => {
history.go(-index);
return;
}
return { navigateTo, navigateBack };
}
export default useNavigate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment