0

I have a react application that is hosted inside another application that manages authentication.

In my application I can see via a web service if the user is authenticated or not.

What I want to do is redirect the user to the main application if they are not authenticated.

My homepage is something like: "/BigApp/MyApp"

I would like to redirect the user to "/BigApp"

which will handle the authentication.

BigApp is not part of MyApp, it just has a link to MyApp.

I already tried using Redirect and tried to go up one level.

From what I understand Redirect only works with the components you have given a route.

import { Redirect } from 'react-router-dom'
...
<Redirect to='../' />

When it redirects it stays in the same URL "/BigApp/MyApp"

Is there any way to achieve this using react router?

printthis
  • 141
  • 3
  • 11

1 Answers1

1

Unfortunatelly, there's no support, within the <Redirect>, to redirect to a external URL.

The way that you tried didn't worked because routes doesn't work as folders. Other point is that, as the react-router just works with a given group of routes(as you said), it won't work from "outside that box".

What you could is use the window.location.assign() method, that redirects your page to a given url passed as parameter.

Snippet below:

const App = () => {
  return <button onClick={() => {window.location.assign("https://stackoverflow.com")}}>Click Here to Redirect</button>
}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
reisdev
  • 3,215
  • 2
  • 17
  • 38
  • Thanks, for the response. The thing is I am not using a button. I get the response from a fetch request and then I need to redirect the user. – printthis Aug 20 '19 at 22:37
  • 1
    You can call the method `window.location.assign()` within any function. The call inside the `onClick` of a button was just a example. – reisdev Aug 20 '19 at 22:39
  • Thanks, I ended up using window.open('http://google.com', "_self", "", false); – printthis Aug 22 '19 at 17:34
  • @JoseLaboy If this answer helped you in any way, feel free to mark it as the solution – reisdev Aug 22 '19 at 20:04