React-Router External link
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
useNavigate: Navigate to external Link
window.location.href = "https://wwww.google.com?q=ABC";
How do I redirect to an External Link in react?
Issues
- I don't know why but you don't seem to use
Link
components consistently in your app; when using anchor (<a>
) tags these types of links will reload the page and your app. A similar issue occurs when you manually set thewindow.location.href
. - The
Image
wasn't correctly accessing the passed route state.
Solution
App
Reorder your routes from more specific to least specific, and remove the link from within the Switch
component, only Route
and Redirect
components are valid children.
function App(props) {
return (
<>
<Router>
<Switch>
<Route path="/gallery" component={GalleryList} />
<Route path="/image" component={Image} />
<Route path="/" component={Home} />
</Switch>
</Router>
</>
);
}
Home
Use Link
component to enter the gallery.
import { Link } from "react-router-dom";
...
<Link to="/gallery">
<h4>Click Here to Enter Gallery!</h4>
</Link>
GallerayList
Use Link
component for the link back home.
import { Link } from "react-router-dom";
...
<Link to="/">Home</Link>
GalleryContainer
Refer to image source consistently, i.e. src
. Pass along also the image id
in route state, using a Link
.
const GalleryConatiner = (props) => {
return (
// generates the gallery list!
<ul>
<li className={styles["gallery-list"]}>
<Link
to={{ pathname: "/image", state: { id: props.id, src: props.src } }}
>
<div
className={styles["div-gallery"]}
style={{
backgroundImage: `url(${props.src})`,
height: 250,
backgroundSize: "cover"
}}
></div>
</Link>
</li>
</ul>
);
};
src/Public/Image
Use a Link
for the link back to the gallery. Use the useLocation
hook to access the passed route state.
import { Link, useLocation } from 'react-router-dom';
const Image = (props) => {
const { state: { id, src } = {} } = useLocation();
return (
<section>
<h1 className={styles["h1-wrapper"]}>Image :{id}</h1>
<div className={styles.wrapper}>
<Link to="/gallery">BACK TO GALLERY</Link>
<ImageContainer id={id} key={id} src={src} />
</div>
</section>
);
};
src/Public/ImageContainer
It isn't clear what your plan is for this component and clicking on the div
rendering the passed image as a background so just remove the window.location.href
logic with history.push
if you want to navigate elsewhere. You can access the history
object via the useHistory
React hook.
Demo
React route to an external link
Just use the good old anchor tags.
React-router is a routing system for a Single-Page Application. That all the routes should be defined in your page and be encapsulated within your app.
For external links, it's okay to use anchor
tags.
<a href="www.example.com/help" />
The rule of thumb here would be :-
- If the link is within your app, use
React-Router
. - If not, use
anchor
tags
Navigate to external link in react js
Try this and let me know if you face any issues.
Here you can use window.location.replace too while i write window.location because it allows the user to go back to the route that redirected them.
handleSubmit = () => { if(registered){ window.location.href = 'https://google.com'; }}
React (5): Make route navigate to an external link
react-router-dom
only deals with internal routing & navigation within a React app. If you want are trying to navigate/redirect to a URL that is external to your app from a matched route then I suggest using window.open
and open in a new browser context, like a new window or tab. You can create a custom component to do this as a mounting effect.
Example:
import { useHistory } from 'react-router-dom';
const RedirectExternal = ({ to }) => {
const history = useHistory();
React.useEffect(() => {
window.open(to, "_blank", "noreferrer");
// use timeout to move back navigation to end of event queue
setTimeout(history.goBack);
}, [history, to]);
return null;
};
Usage:
<Link to="/example">www.example.com</Link>
...
<Switch>
<RedirectExternal from="/example" to="https://www.example.com" />
<Route path="/">
<PageLayout>
<LandingPage />
</PageLayout>
</Route>
</Switch>
It might just be easier to link to the external page directly though.
<a href="https://www.example.com" rel="noreferrer" target="_blank">
www.example.com
</a>
Related Topics
Get Elements by Attribute When Queryselectorall Is Not Available Without Using Libraries
When Should I Use Jquery's Document.Ready Function
Document.Createelement("Script") Synchronously
Javascript: How to Join/Combine Two Arrays to Concatenate into One Array
Passing Custom Props to Router Component in React-Router V4
Angularjs Uncaught Error: [$Injector:Modulerr] When Migrating to V1.3
Angularjs Ui-Router Login Authentication
Chrome Desktop Notification Example
Check Whether a String Matches a Regex in Js
Cross Browser JavaScript (Not Jquery...) Scroll to Top Animation
Is the Underscore Prefix for Property and Method Names Merely a Convention
How to Upload a File with the Js Fetch API
Passing an Array as a Function Parameter in JavaScript
Why Does a While Loop Block the Event Loop