score:51
I actually ended up building my own Component. <Redirect>
It takes info from the react-router
element so I can keep it in my routes. Such as:
<Route
path="/privacy-policy"
component={ Redirect }
loc="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies"
/>
Here is my component incase-anyone is curious:
import React, { Component } from "react";
export class Redirect extends Component {
constructor( props ){
super();
this.state = { ...props };
}
componentWillMount(){
window.location = this.state.route.loc;
}
render(){
return (<section>Redirecting...</section>);
}
}
export default Redirect;
EDIT -- NOTE:
This is with react-router: 3.0.5
, it is not so simple in 4.x
score:-5
I was able to achieve a redirect in react-router-dom using the following
<Route exact path="/" component={() => <Redirect to={{ pathname: '/YourRoute' }} />} />
For my case, I was looking for a way to redirect users whenever they visit the root URL http://myapp.com
to somewhere else within the app http://myapp.com/newplace
. so the above helped.
score:-5
You can now link to an external site using React Link by providing an object to to
with the pathname
key:
<Link to={ { pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies' } } >
If you find that you need to use JS to generate the link in a callback, you can use window.location.replace()
or window.location.assign()
.
Over using window.location.replace()
, as other good answers suggest, try using window.location.assign()
.
window.location.replace()
will replace the location history without preserving the current page.
window.location.assign()
will transition to the url specified, but will save the previous page in the browser history, allowing proper back-button functionality.
https://developer.mozilla.org/en-US/docs/Web/API/Location/replace https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
Also, if you are using a window.location = url
method as mentioned in other answers, I highly suggest switching to window.location.href = url
.
There is a heavy argument about it, where many users seem to adamantly want to revert the newer object
type window.location
to its original implementation as string
merely because they can (and they egregiously attack anyone who says otherwise), but you could theoretically interrupt other library functionality accessing the window.location
object.
Check out this convo. It's terrible. Javascript: Setting location.href versus location
score:-2
If you are using server side rending, you can use StaticRouter
. With your context
as props
and then adding <Redirect path="/somewhere" />
component in your app. The idea is everytime react-router matches a redirect component it will add something into the context you passed into the static router to let you know your path matches a redirect component. now that you know you hit a redirect you just need to check if thats the redirect you are looking for. then just redirect through the server. ctx.redirect('https://example/com')
.
score:-1
Using React with Typescript you get an error as the function must return a react element, not void
. So I did it this way using the Route render method (and using React router v4):
redirectToHomePage = (): null => {
window.location.reload();
return null;
};
<Route exact path={'/'} render={this.redirectToHomePage} />
Where you could instead also use window.location.assign()
, window.location.replace()
etc
score:0
FOR V3, although it may work for V4. Going off of Eric's answer, I needed to do a little more, like handle local development where 'http' is not present on the url. I'm also redirecting to another application on the same server.
Added to router file:
import RedirectOnServer from './components/RedirectOnServer';
<Route path="/somelocalpath"
component={RedirectOnServer}
target="/someexternaltargetstring like cnn.com"
/>
And the Component:
import React, { Component } from "react";
export class RedirectOnServer extends Component {
constructor(props) {
super();
//if the prefix is http or https, we add nothing
let prefix = window.location.host.startsWith("http") ? "" : "http://";
//using host here, as I'm redirecting to another location on the same host
this.target = prefix + window.location.host + props.route.target;
}
componentDidMount() {
window.location.replace(this.target);
}
render(){
return (
<div>
<br />
<span>Redirecting to {this.target}</span>
</div>
);
}
}
export default RedirectOnServer;
score:0
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
function App() {
return (
<Router>
<Route path="/" exact>
{window.location.replace("http://agrosys.in")}
</Route>
</Router>
);
}
export default App;
score:0
In React Route V6 render props removed. should be a redirect component.
RedirectUrl:
const RedirectUrl = ({ url }) => {
useEffect(() => {
window.location.href = url;
}, [url]);
return <h5>Redirecting...</h5>;
};
Route:
<Routes>
<Route path="/redirect" element={<RedirectUrl url="https://google.com" />} />
</Routes>
score:1
I don't think React-Router provides this support. The documentation mentions
A < Redirect > sets up a redirect to another route in your application to maintain old URLs.
You could try using something like React-Redirect instead
score:1
To expand on Alan's answer, you can create a <Route/>
that redirects all <Link/>
's with "to" attributes containing 'http:' or 'https:' to the correct external resource.
Below is a working example of this which can be placed directly into your <Router>
.
<Route path={['/http:', '/https:']} component={props => {
window.location.replace(props.location.pathname.substr(1)) // substr(1) removes the preceding '/'
return null
}}/>
score:1
I think the best solution is to just use a plain old <a>
tag. Everything else seems convoluted. React router is designed for navigation within single page applications, so using it for anything else doesn't make a whole lot of sense. Making an entire component for something that is already built into the <a>
tag seems... silly?
score:2
I'm facing same issue. Solved it using by http://
or https://
in react js.
Like as:
<a target="_blank" href="http://www.example.com/" title="example">See detail</a>
score:3
I solved this on my own (in my web app) by adding an anchor tag and not using anything from React router, just a plain anchor tag with a link as you can see in the picture screenshot of using anchor tag in a react.js app without using react router
Basically, you are not routing your user to another page inside your app so you must not use the internal router but use a normal anchor.
Although this is for a non-react-native solution but you can try.
score:3
You can use for your dynamic url
<Link to={{pathname:`${link}`}}>View</Link>
score:6
I had luck with this:
<Route
path="/example"
component={() => {
global.window && (global.window.location.href = 'https://example.com');
return null;
}}
/>
score:7
The most simple solution is to use a render function and change the window.location
.
<Route path="/goToGoogle"
render={() => window.location = "https://www.google.com"} />
If you want a small reusable component you can just extract it like this:
const ExternalRedirect = ({ to, ...routeProps }) => {
return <Route {...routeProps} render={() => window.location = to} />;
};
and then use it (e.g. in your router switch) like this:
<Switch>
...
<ExternalRedirect exact path="/goToGoogle" to="https://www.google.com" />
</Switch>
score:9
Using some of the info here, I came up with the following component which you can use within your route declarations. It's compatible with React Router v4.
It's using typescript, but should be fairly straight-forward to convert to native javascript:
interface Props {
exact?: boolean;
link: string;
path: string;
sensitive?: boolean;
strict?: boolean;
}
const ExternalRedirect: React.FC<Props> = (props: Props) => {
const { link, ...routeProps } = props;
return (
<Route
{...routeProps}
render={() => {
window.location.replace(props.link);
return null;
}}
/>
);
};
And use with:
<ExternalRedirect
exact={true}
path={'/privacy-policy'}
link={'https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}
/>
score:9
I went through the same issue. I want my portfolio to redirect to social media handles. Earlier I used {Link} from "react-router-dom".
That was redirecting to the sub directory as here,
Link can be used for routing web pages within a website. If we want to redirect to an external link then we should use an anchor tag. Like this,
score:64
It doesn't need to request react router. This action can be done natively and it is provided by the browser.
just use window.location
With React Hooks
const RedirectPage = () => {
React.useEffect(() => {
window.location.replace('https://www.google.com')
}, [])
}
With React Class Component
class RedirectPage extends React.Component {
componentDidMount(){
window.location.replace('https://www.google.com')
}
}
Also, if you want to open it in a new tab:
window.open('https://www.google.com', '_blank');
score:111
There is no need to use <Link />
component from react-router.
If you want to go to external link use an anchor tag.
<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>
score:143
With Link component of react-router you can do that. In the "to" prop you can specify 3 types of data:
- a string: A string representation of the Link location, created by concatenating the location’s pathname, search, and hash properties.
- an object: An object that can have any of the following properties:
- pathname: A string representing the path to link to.
- search: A string representation of query parameters.
- hash: A hash to put in the URL, e.g. #a-hash.
- state: State to persist to the location.
- a function: A function to which current location is passed as an argument and which should return location representation as a string or as an object
For your example (external link):
https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
You can do the following:
<Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />
You can also pass props you’d like to be on the such as a title, id, className, etc.
score:264
Here's a one-liner for using React Router to redirect to an external link:
<Route path='/privacy-policy' component={() => {
window.location.href = 'https://example.com/1234';
return null;
}}/>
It uses React pure component concept to reduce the component's code to a single function that, instead of rendering anything, redirects browser to an external URL.
Works both on React Router 3 and 4.
Source: stackoverflow.com
Related Query
- React Router Link reloading page : Conflict with external event
- React Router Invariant failed when Route or Link is used in an external package
- External link not working when using LINK from react router dom
- Route redirecting to an external link caught in a loop in react router
- Pass object through Link in react router
- Open link in new tab in react router programmatically
- React Router work on reload, but not when clicking on a link
- History.push a link to a new tab with react router
- How to pass params into link using React router v6?
- In react router v4 how does one link to a fragment identifier?
- react router relative link does not link properly
- Using React Router and Webpack 2 how to require external libraries only on certain routes?
- React router Link not causing component to update within nested routes
- Can I use react router Link with CardActionArea?
- Why is state undefined when passed through React Router Link Component?
- React router Link absolute path
- React Router browserHistory.push open link in a new tab
- React Router doesn`t load external html files
- Need to navigate link while clicking material ui table row in React Router 4
- React Router redirect hash link
- How to link to nested routes in React Router
- react router dom link with params dont allways work
- Testing React Router with Link
- React Router or Link Not Rendered
- Passing data using state in Link tag in React router
- How can I open an external link in new tab in react native?
- Open external link with function in React
- React Router Link doesn't work with LeafletJS
- react router Link doesn't cause rerender when visited on the same path
- React Router Error related to Link To
More Query from same tag
- Axios request returning promise Object
- Private Route in react-router v6 taking Authentication using redux
- React chained setState breaking render
- Possiblity to find an object based on id then render it inside a react component
- Marmelab react-admin x-total-count how to add new headers
- Display image from flask send_file function in ReactJS
- Checking selected value of a react 'select' using Enzyme
- React TypeError: undefined onSubmit
- Trouble understanding React setState asychronicity
- reactjs createRef not work in component arrays
- Javascript Map Function Not Storing Correct Value
- Access rootState within async effect without specifying payload first
- React pass a prop that has an internally bound target
- Create a firestore doc for each auth user in Nextjs (only using sign in with Google)
- Higher Order Component - listening for onChange
- Jest with Styled Components error: Syntax error parsing expected css: missing '}'
- Get the value of checkbox using ref in React
- map not a function using react hooks
- How to push incomplete parts in react
- How to use redux saga in editable table efficiently
- How can I use react hook useReducer more effectively?
- React: How to send data on Popup close?
- React-Bootstrap not working for server-side render React App?
- Setting up React / Webpack / Babel and creating custom components
- React hooks array specific problem with structure
- How Do I Get Menu Items in Select Menu for ReactJS MUI?
- Is React context provider not mounted before child components?
- Stripe with React JS
- How to structure my API call, and where to put the key and query?
- Unmount cycle behavior in react hooks