Dana Chen
Dana Chen

Reputation: 216

Pass props to HOC in typescript

I have a layout HOC call "withLayout"

interface WithLayoutProps {
  isHomePage?: boolean;
}

const withLayout = <P extends object>(Component: ComponentType<P>) => (
  props: P & WithLayoutProps,
): ReactElement => {

  return (
    <div>
      {!!isHomePage?<Header1 />:<Header2 />} //How the home page pass the "isHomePage" to there?
      <main>
        <Component {...props} />
      </main>
    </div>
  );
};

export default withLayout;

All the page is layout with this component

const Home: NextPage = withLayout(() => {

  return (
    <div>home</div>
  )
})


But in the Home page, we need the different header like <Header1 /> And other Page Use

How could I pass the props isHomePage to the withlayout ?

Upvotes: 1

Views: 1221

Answers (1)

Joseph D.
Joseph D.

Reputation: 12174

How could I pass the props isHomePage to the withlayout ?

Just add isHomePage as an extra argument to the HOC.

withLayout is still a normal function so you can have more or few arguments (as needed).

const withLayout = <P extends object>(
  Component: ComponentType<P>,
  isHomePage: boolean = true // extra argument with default value
) => (
  props: P & WithLayoutProps,
): ReactElement => {...};

// usage:
const Home: NextPage = withLayout(
  () => (<div>home</div>)
})

const AboutUs: NextPage = withLayout(
  () => (<div>About Us</div>),
  false // not home page
)

Upvotes: 4

Related Questions