react router dom redirect code example

Example 1: redirect in react

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

const ProtectedComponent = () => {
  if (authFails)
    return <Redirect to='/login'  />
  }
  return <div> My Protected Component </div>
}

Example 2: javascript redirect

window.location.href = "http://mywebsite.com/home.html";

Example 3: react redirect to url

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>

Example 4: redirect react router

<Route exact path="/">
  {loggedIn ? <Redirect to="/profile" /> : <HomePage />}
</Route>

Example 5: react router redirect

<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>

Example 6: react-router-dom redirect on click

import { useHistory } from 'react-router-dom';

function app() {
  let history = useHistory();

  const redirect = () => {
    history.push('/your-path')
  }

  return (
    <div>
      <button onClick={redirect}>Redirect</button>
    </div>
  )
}