I'm learning NextJS / TypeScript atm and encountered a type error. I have the following component
interface LayoutProps {
children: React.ReactNode;
title: string;
keywords: string;
description: string;
}
const Layout: React.FC<LayoutProps> = ({ title, description, keywords, children }) => {
return (
<div>
<Head>
<title>{title}</title>
<meta name="description" content={description} />
<meta name="keywords" content={keywords} />
</Head>
<Header />
<div className={styles.container}>{children}</div>
<Footer />
</div>
);
};
but when I use Layout to wrap any component, TS complains with the below:
interface HomePageProps {}
const HomePage: React.FC<HomePageProps> = ({}) => {
return (
// Type '{ children: Element; }' is missing the following properties from type 'LayoutProps'
<Layout>
<h1>Home Page</h1>
</Layout>
);
};
I've tried passing defaultProps and made the children prop optional such as the below, but it didnt work.
interface LayoutProps {
children?: React.ReactNode | null;
title: string;
keywords: string;
description: string;
}
const Layout: React.FC<LayoutProps> = ({ title = 'title', description = 'desc', keywords = 'kw', children = null }) => {...}
I'm stuck at this point and will appreciate any help / pointers. Thank you so much!
CodePudding user response:
You have to pass the props to Layout
:
interface HomePageProps {}
const HomePage: React.FC<HomePageProps> = ({}) => {
return (
<Layout title="title" description="desc" keywords="kw">
<h1>Home Page</h1>
</Layout>
);
};
Also, keep in mind that the children
prop represents the children in your component call, so <h1>Home Page</h1>
in this case