score:0
i couldn't find a simple way to do that with react router. as @mike wrote you should use anchor (<a>
tags) when sending the user to external site.
i created a custom <link>
component to dynamically decide whether to render a react-router <link>
or regular <a>
tag.
import * as react from "react";
import {link, linkprops} from "react-router-dom";
const reloadablelink = (props: linkprops & { forcereload?: boolean }) => {
const {forcereload, ...linkprops} = props;
if (forcereload)
return <a {...linkprops} href={string(props.to)}/>;
else
return <link {...linkprops}>
{props.children}
</link>
};
export default reloadablelink;
score:1
as pointed by @mike 'pomax' kamermans, you can just use to navigate to external link.
i usually do it this way, with is-internal-link
import react from 'react'
import { link as reactrouterlink} from 'react-router-dom'
import { isinternallink } from 'is-internal-link'
const link = ({ children, to, activeclassname, ...other }) => {
if (isinternallink(to)) {
return (
<reactrouterlink to={to} activeclassname={activeclassname} {...other}>
{children}
</reactrouterlink>
)
}
return (
<a href={to} target="_blank" {...other}>
{children}
</a>
)
}
export default link
disclaimer: i am the author of this is-internal-link
score:1
i had the same issue and my research into the issue uncovered that i could simply use an "a href" tag. if using target="_blank" you should write your link this...
<a href="https://yourlink.com" target="_blank" rel="noopener noreferrer">your link</a>
score:1
you can try and create a link element and click it from code. this work for me
const navigateurl = (url) => {
let element = document.createelement('a');
if(url.startswith('http://') || url.startswith('https://')){
element.href = url;
} else{
element.href = 'http://' + url;
}
element.click();
}
score:6
you don't need react-router
for external links, you can use regular link elements (i.e. <a href="..."/>
) just fine.
you only need react-router
when you have internal navigation (i.e. from component to component) for which the browser's url bar should make it look like your app is actually switching "real" urls.
edit because people seem to think you can't use an <a href="..."
if you need to "do work first", an example of doing exactly that:
render() {
return <a href={settings.externallocation} onclick={evt => this.leave(evt)}/>
}
async leave(evt) {
if (this.state.finalized) return;
evt.preventdefault();
// do whatever you need to do, but do it quickly, meaning that if you need to do
// various things, do them all in parallel instead of running them one by one:
await promise.all([
utils.doallthemetrics(),
user.logoutuser(),
store.cleanup(),
somelib.whatever(),
]);
// done, let's leave.
this.setstate({ finalized: true }), () => evt.target.click());
}
and that's it: when you click the link (that you styled to look like a button because that's what css is for) react checks if it can safely navigate away as a state check.
- if it can, it lets that happen.
- if it can't:
- it prevents the navigation of occurring via
preventdefault()
, - does whatever work it needs to do, and then
- marks itself as "it is safe to leave now", then retriggers the link.
- it prevents the navigation of occurring via
score:27
as pointed out in the comments to this answer, default way of solving this would be to use anchor element (the a
tag) with href
attribute that points at the destination url that you'd like to route the user to. a button that has appearance of a button but behavior or an anchor is pretty much a web anti-pattern. see more info in this answer: https://stackoverflow.com/a/1667512/1460905.
that said, there certainly is a potential scenario when a web app needs to perform some action and only then redirect the user. in this case, if primary action the user takes is submitting some data or really performing an action, and redirect is more of a side-effect, then the original question is valid.
in this case, why not use location
property of window
object? it even provides a nice functional method to go to external location. see the ref.
so, if you have a component, say
class button extends component {
render() {
return (
<button onclick={this.handleclick.bind(this)} />
);
}
}
then add handleclick
that would make the component look like
class button extends component {
handleclick() {
// do something meaningful, promises, if/else, whatever, and then
window.location.assign('http://github.com');
}
render() {
return (
<button onclick={this.handleclick.bind(this)} />
);
}
}
no need to import window
since it's global. should work perfectly in any modern browser.
also, if you have a component that is declared as a function, you may possibly use the effect hook to change location when state changes, like
const button = () => {
const [clicked, setclicked] = usestate(false);
useeffect(() => {
if (clicked) {
// do something meaningful, promises, if/else, whatever, and then
window.location.assign('http://github.com');
}
});
return (
<button onclick={() => setclicked(true)}></button>
);
};
Source: stackoverflow.com
Related Query
- React Router always redirect me to a different url
- react-router redirect to a different domain url
- React Router v4 - Redirect to same route with different query params
- Why React Router NavLink prop exact (v5) vs. end (v6) lead to different result with trailing slash in url
- React router redirect to a deeper url
- React Router (Dom) v4 redirect to different route upon input enter key press
- React Router v6 redirect when there are not any url queryString parameters
- React Router with Meteor: How to remove code param from URL after redirect from OAuth without reload
- React Router | different component in same url
- React Router redirect when url isn't correct
- redirect to different route if input was submitted - React Router
- React router - How to redirect to child component if parent component path is entered in url
- React Router Link to same component with different URL not re-rendering
- React router redirect whenever there is an uppercase in URL
- How to create React router redirect url
- React Router Dom doesn't redirect but the URL changes
- URL Redirect In Redux Action With Server-Side React & React Router v4
- React Router v5: 404 when use url directly or refresh page on route different from "/"
- How to redirect to different component with URL in React
- React router changes url but not view
- How to redirect in React Router v6?
- React router redirect after action redux
- React router private routes / redirect not working
- How to redirect from axios interceptor with react Router V4?
- React Router v4 Redirect not working
- react routing is able to handle different url path but tomcat returns 404 not available resources
- React router - Update URL hash without re-rendering page
- React Router Redirect drops param
- React Router v4 Redirect unit test
- Redirect to previous path on login - React Router v4
More Query from same tag
- How do I make a form submission save data in a useState hook variable?
- React Redux Saga Event Channel Cancel
- React State value not updated in Arrow functional component
- Aggregate results from multiple Promises in React Hook
- Why is this array undefined in React?
- Ag-Grid - How to make two horizontal scrolls in the same grid?
- pass data blade (laravel) to react component
- data structure to store single parent family tree in react
- gulp-eslint not throwing any error on console
- With redux form how can I normalize and allow only positive integers on an input type number?
- How to toggle on Order in ReactJS
- React/Styled-Components: Need to hand roll a dropdown with multiple versions that a developer could use by passing a type in
- how to use react-router for dynamic url
- Axios request on frontend doesnt load the data I need from MongoDB database on backend
- react-tag-autocomplete with redux form
- how to disable radio button in react
- How to checked checkbox using state in react in class based components
- Make material-ui grids wrap, on larger screens
- React Loading Msg
- webpage disappears whenever I type anything in the input
- I try to sort the value and update the same of both columns by onclick of name and Lname(its TH)
- How to send props to click handler - React JS
- Amplify GraphQL get item from other field than ID
- React router with basename and webpack initial url
- React MUI Multiple Select with Checkboxes not Check marking Initial Selected Options
- Axios only called once inside self-invoking function (Internet Explorer)
- how to access props in react quill image handler
- how to calculate width of component in react js?
- What is the correct way to set state in React
- Typescript declaration merging to expand or override module type or interface property