LoginSignup
1
0

【React(TypeScript)】React Routerでログインチェック、未ログインならログイン画面遷移、さらにログイン後にリダイレクトする

Last updated at Posted at 2023-12-16

概要

React Routerで画面遷移前に共通処理を入れる方法は以前の記事でできるようになりました。
今回は画面遷移前にログインチェックを行い、未ログインの場合はログイン画面に遷移させ、さらにログイン後に元々の画面遷移先にリダイレクトする方法をマイベストプラクティスとして共有させていただきたいと思います。

Router.tsx

PrivateRoutesで未ログインの場合はNavigateでログイン画面に画面遷移させます。この時、stateでリダイレクト先を渡します。リダイレクト先はuseLocation()を使ってlocation.pathnameで取得しています。

const PrivateRoutes = () => {
  const location = useLocation()
  
  // 未ログインチェック
  // (isLoginを判定する処理は省略してます)
  if (isLogin === false) {
    return (
      <Navigate to='/signin' state={{ redirectPath: location.pathname }} />
    )
  }
  return <Outlet />
}

const Router = () => (
  <BrowserRouter>
    <Routes>
      <Route path="signin" element={<SignIn />} />
      {/* PrivaeRoutes内に設定された画面はサインインが必須になる */}
      <Route element={<PrivateRoutes />}>
        <Route path="home" element={<Home />} />
      </Route>
      <Route path="*" element={<Error404 />} />
    </Routes>
  </BrowserRouter>
)

export default Router

SignIn.tsx

ログイン成功後、stateからリダイレクト先を取得できればリダイレクトさせます。

type State = {
  redirectPath?: string
}

const SignIn = () => {
  const location = useLocation()
  const state = location?.state as State

  function handleSignInButton() {
    // サインイン処理
    
    (省略)

    // サインイン成功後
    
    const redirectPath = state?.redirectPath
    // リダイレクト先が指定されている場合
    if (redirectPath != null) {
      navigate(redirectPath)
    }
    navigate('/home')
  }

  return (
  
    (省略
    
    <button onClick={() => { handleSignInButton() }}>
      サインイン
    </button>
  )
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0