Skip to content Skip to sidebar Skip to footer

How To Redirect User To Url React

I have a question that sounds quite simple but I just can't find a solution. I have tried multiple answers on similar questions for both standard JS and specifically for React, but

Solution 1:

If you use something like React Router: Declarative Routing for React.js, which is the right way to do redirects, you can use Redirect API in two ways:

  • Using the <Redirect to="" />
  • Using a higher order function withRouter()

For using <Redirect to="" />, all you need to do is, with a condition or inside the component, use:

<Redirect to="/somewhere/else" />
{/* Or in your case... */}
<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>

Using withRouter():

import React from "react";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class App extends React.Component {

  componentDidMount() {
    // Check user logged in and redirect somewhere.
    if (loggedIn) {
      // Something like this.
      location.replace("/dashboard");
    }
  }

  render() {
    const { match, location, history } = this.props;
    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const App = withRouter(App);

Solution 2:

Every route for your app has to be wrapped in a HOC inside which will check whether the user is authenticated or not in componentDidMount. If not authenticated, you redirect to the login screen.

In case, your app support token for authentication: In the componentDidMount of the HOC, you could check if the token cached in some browser storage is still valid or not, and based on the validity you decide to redirect to the login screen

What I prefer:

I find, using Redirect of react-router-dom to be more declarative. Check the usage here: https://reactrouter.com/web/api/Redirect


Solution 3:

Just add this code window.location.replace('new url') Whenever this line gets executed the window will be replaced to the new defined URL! :D


Solution 4:

import { useAuthState } from 'react-firebase-hooks/auth';

firebase.initializeApp({
  //your key from firebase
})

const [user] = useAuthState(auth); 

<section>
      {user ? <ChatRoom /> : <SignIn />}
</section> 

Post a Comment for "How To Redirect User To Url React"