Home > Software design >  Is there <Navigate> as react-router-dom?
Is there <Navigate> as react-router-dom?

Time:04-04

In parent

import LoginPage from "pages/admin";

export function Home() {
  return <LoginPage />;
}

In child

import { useRouter } from "next/router";


export default function LoginPage() {
  const router = useRouter();
  return (router.replace("/users");)

I got JSX error.
Because child is not used JSX.

But in react-router-dom, There is <Navigate>.
So in that case, it can fix.

Is there <Navigate> as react-router-dom in Next.js?

CodePudding user response:

You can use router.push for redirections:

import { useEffect } from 'react'
import { useRouter } from 'next/router'

// Here you would fetch and return the user
const useUser = () => ({ user: null, loading: false })

export default function Page() {
  const { user, loading } = useUser()
  const router = useRouter()

  useEffect(() => {
    if (!(user || loading)) {
      router.push('/login')
    }
  }, [user, loading])

  return <p>Redirecting...</p>
}

Next documentation: https://nextjs.org/docs/api-reference/next/router

Custom JSX component

If you need a component to do this:

import { useEffect } from 'react'
import { useRouter } from 'next/router'

function Redirect({ to }) {
  const router = useRouter()

  useEffect(() => {
    router.push(to)
  }, [])

  return null
}

Then just use it as a react-router <Redirect to="" />

  • Related