BluePilot
BluePilot

Reputation: 403

How do I redirect using a relative URL?

I am trying to redirect a Sign Out button from a dropdown on my page. When I click on the sign out as of right now it will go to localhost:3000/signout. I have tried:

export const SIGNOUT="redirect=www.google.com";

and it will simply replace the URL as localhost:3000/redirect=www.google.com.

I have tried :

<Route exact path={SIGNOUT}>
    <Redirect to={www.google.com}/>
</Route>
export const SIGNOUT="www.google.com";

This will redirect to google.com upon loading and won't even let me load my own webpage:

export const SIGNOUT= window.location.replace("http://www.google.com");

urlLists.js

export const SIGNOUT= "www.google.com";

App.js

import {SIGNOUT} from "./utils/urlLists";

class App extends Component {
    render() {
        const {location} = this.props
        return (
            <Switch>
                <Route exact path={SIGNOUT}>
                    <Redirect to={HOME}/>
                </Route>
            </Switch>
        );
    }
}

export default withRouter(App);

I expect the results of this to redirect to Google upon clicking on the Sign Out dropdown option.

The actual result is either a redirection to:

localhost:3000/www.google.com

or the Google page is loaded and my localhost:3000 does not.

Upvotes: 0

Views: 1769

Answers (3)

tifla
tifla

Reputation: 39

You can try this:

import React from 'react'
import  { Redirect } from 'react-router-dom'

const ProtectedComponent = () => {
 if (authFails)
    return <Redirect to='redirect=www.google.com'  />
}
return <div> My Protected Component </div>
}

Upvotes: 0

automasean
automasean

Reputation: 421

The idea is to redirect inside your Home component. Take a look at this sample implementation.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function Home() {
  return (
    <div className="App">
      <h1>Hello World</h1>
      <button
        name="sign-out"
        onClick={() => {
          // sign user out here
          window.location.assign("www.google.com");
        }}
      >
        Sign Out
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Home />, rootElement);

The Redirect component is nice for redirecting to an internal route. However, if you're kicking the user out of your app you should use something else like window.location.assign().

Upvotes: 2

Isabella Wang
Isabella Wang

Reputation: 81

Whatever included in the "" is the thing added to the domain. For example export const SIGNOUT= window.location.replace("google"); will become localhost:3000/google.

If you want to use "www.google.com", try to import it as a thing of its own at the beginning of the page, like "import Google from "www.google.com", then use the {Google} element.

Upvotes: 0

Related Questions