Reputation: 5016
I've found this solution for redirecting to an external link, and it has worked for one of my pages.
But for a different page it is no longer working, and I'm not sure why.
redirect.jsx
:
import React from "react";
import { BrowserRouter, Route } from 'react-router-dom'
export default class Redirect extends React.Component {
render() {
return (
<Route path='/hello' component={() => {
window.location.href = "example.com";
return null;}}/>
);
}
}
test.jsx
:
import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter} from 'react-router-dom'
import MainExport from './components/redirect.jsx';
ReactDOM.render(
<BrowserRouter>
<div>
<MainExport />
</div>
</BrowserRouter>, document.getElementById("content")
);
test.html
:
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div className="App">
<div id="content" />
<div/>
<script src="dist/bundle/test.bundle.js" type="text/javascript"></script>
</body>
</html>
When I load this page, I expect it to redirect to the URL "/hello" and display the page from "example.com".
Instead, it does nothing.
What am I doing wrong?
EDIT: Some of the answers have been helpful, but none of them have worked yet.
I've found that using the Redirect
component renders and does the redirect, but does it in some way such that my Flask server doesn't actually serve the file. All I see is a blank screen.
Changing the name to MyRedirect
also did not make it work.
Using render
instead of component
also did not seem to have an impact.
The redirect is still not taking place.
(I'm also still not seeing any error messages in the JS console or on the server side.)
Upvotes: 0
Views: 1649
Reputation: 5016
It looks like I don't need to use React at all: to do the redirect I can use plain javascript and just do window.location.href = "example.com"
Upvotes: 0
Reputation: 4252
First things first. The router handles the routes as the name says xDDDD but with in the scopes if the usaw is going to get out of the scope of the app. Add the anchor tags in the button the user is going to click.
Note: they should be “a” tags for those a that targets the redirecting out side to f you domain links won’t work. But f you still wanna see that on yow BrowserRouter then on the Route Component use render, instead of component
<Route path=“the-path” render={()=>window.location-and-stuff} />
Upvotes: 0
Reputation: 5342
You don't need to create your own Redirect component if you're using react-router. They already made one for you.
You just need to import it and render it to be redirected.
import React from 'react'
import { Redirect } from 'react-router-dom'
export default () => <Redirect to="/hello" />
Upvotes: 0