Next.js Discord

Discord Forum

Typescript notation for wrapper element

Answered
Savannah posted this in #help-forum
Open in Discord
SavannahOP
I have a client component called AuthRequired that can be wrapped around other components that require authentication. Here's the definition:

"use client"

import useAuth from "@/hooks/useAuth"
import { useRouter } from "next/router"
import React from "react"

function AuthRequired({ element }: {element: () => React.JSX.Element}) {
  const { user } = useAuth()
  const router = useRouter()  

  if (!user) {
    router.push("/")
  }

  return element
}

export default AuthRequired


I have other component in which I want to use this AuthRequired functionality. Here's the rough definition:

"use client"

...
import AuthRequired from "@/components/AuthRequired"


function Library() {
  return (
    ...
  )
}

export default AuthRequired(Library)


As you can see, I am wrapping Library component with AuthRequired right in the end that results in this ts error (screenshot attached)
Answered by Ray
also, I think your code doesn't work as expected
try this
"use client";

import { useRouter } from "next/navigation";
import { FC } from "react";

function authRequired<T extends object>(Component: FC<T>) {
  return function AuthRequired(props: T) {
    const { user } = useAuth()
    const router = useRouter();

    if (!user) {
      router.push("/");
      return null;
    }

    return <Component {...props} />;
  };
}

function Library() {
  return (
    ...
  )
}

export default authRequired(Library);
View full answer

8 Replies

SavannahOP
Why is this happening? I tried using JSX.Element and React.JSX.Element. Both give the same ts error :/
@Savannah Why is this happening? I tried using `JSX.Element` and `React.JSX.Element`. Both give the same ts error :/
because the props is an object of { element }: {element: () => React.JSX.Element}
so it should be export default AuthRequired({ element: Library })
also, I think your code doesn't work as expected
try this
"use client";

import { useRouter } from "next/navigation";
import { FC } from "react";

function authRequired<T extends object>(Component: FC<T>) {
  return function AuthRequired(props: T) {
    const { user } = useAuth()
    const router = useRouter();

    if (!user) {
      router.push("/");
      return null;
    }

    return <Component {...props} />;
  };
}

function Library() {
  return (
    ...
  )
}

export default authRequired(Library);
Answer
SavannahOP
Wow dude
Not only you solved my TS error, but you also saved me from hours of debugging the wrapper component