I need to open a link to a new tab after doing some logic.
I have a button like this:
<Button
onClick={handleSubmit}
>
Preview
</Button>
with the handleSubmit() being:
const history = useHistory();
const handleSubmit = () => {
console.log("doing something");
history.push("/some-link")
}
As you can see, with my usecase it wouldn't make sense to use the Link
component.
So, is there a way to push that link to a new tab, using only history.push()
React-router's history is meant to be used just for the navigation of your application and some persistance. I can't see why you need to use it to open a new tab. I think you should use the window object for this.
const handleSubmit = () => {
console.log("doing something");
const win = window.open("/some-link", "_blank");
win.focus();
}
UPDATE: Due to some comments that confirm that it is not neccesary to focus the new window we can make this solution even shorter, like:
const handleSubmit = () => {
console.log("doing something");
window.open("/some-link", "_blank");
}
If you simply want to open a new tab without any state transfer, you can just get the path using useHref
hook (Docs). This is what the <Link>
component internally uses. You can then open it in new tab using window.open
. This would automatically add the basename etc for you.
let href = useHref(to);
window.open(href, '_blank');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With