Categories
React Answers

How to Automatically Redirect After Login with React Router

Spread the love

Oftentimes, we want to automatically redirect the user to another page after the user logged in.

In this article, we’ll look at how to automatically redirect the user to another page after the user logged in with React Router.

Automatically Redirect After Login with React Router

We can automatically redirect after login with React Router.

To do that, we get the history object and call push on it.

For instance, we can write:

fetch('/login', {
  username,
  password
})
  .then(response => response.json())
  .then(data => {
    this.props.history.push("/");
  })

We call this.props.history.push to do the redirect.

The prop is available once we pass the component into the withRouter higher-order component.

Set Types on useState React Hook with TypeScript

To set the state of the useState hook, we can pass in a type parameter with the useState function.

For instance, we can write:

const [user, setUser] = useState<IUser>({ name: 'james' });

IUser is an interface that has the name string property.

For a full example, we can write:

import React, { useState, Dispatch } from 'react';

interface IUser {
  name: string;
}

const App = () => {
  const [user, setUser] = useState<IUser>({ name: 'james' });
  const clickHander = (stateSetter: Dispatch<IUser>) => {
    stateSetter({name : 'james'});
  }

  return (
     <div>
      <button onClick={() => { clickHander(setUser) }}>Change Name</button>
    </div>
  )
}

setUser has the type Dispatch<IUser> .

Dispatch is from the React package.

The type parameter in Dispatch should match the type we pass into useState .

Conclusion

We can automatically redirect after login with React Router.

To do that, we get the history object and call push on it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *