Next.js <Redirect />

A <Redirect /> component like the one from react-router v5.

typescriptjavascript
import { useRouter } from 'next/router'
interface RedirectProps {
to: string
replace?: boolean
}
const Redirect: React.FC<RedirectProps> = ({ to, replace }) => {
const router = useRouter()
useEffect(() => {
router[replace ? 'replace' : 'push'](to)
}, [to, replace])
return null
}

Usage

tsxjsx
const Example = () => {
// Get authentication state from somewhere
const { loggedIn } = useAuth()
if (!loggedIn) return <Redirect to="/login" />
return <ProtectedContent />
}
Created 04/02/21Updated 03/18/23
Found a mistake, or want to suggest an improvement? Edit on GitHub here
and see edit history here