44
loading...
This website collects cookies to deliver better user experience
children
.import React from 'react';
export interface Props {
heading: string;
}
const PostPreview = (props: Props) => {
return (
<div>
<h1>{props.heading}</h1>
{props.children}
</div>
);
};
export default PostPreview;
PostPreview
component has a heading
property. The component is supposed to render the heading
and other components (children
) below the heading. In technical terms this is called Containment.Props
interface only defines the heading, the following error shows up:TS2339: Property 'children' does not exist on type 'Props'.
PropsWithChildren
. It supports a generic type variable, so that we can use our Props
with it:import React, {PropsWithChildren} from 'react';
export interface Props {
heading: string;
}
const PostPreview = (props: PropsWithChildren<Props>) => {
return (
<div>
<h1>{props.heading}</h1>
{props.children}
</div>
);
};
export default PostPreview;
React.FC
specifies a function component and lets us also assign a type variable. It uses PropsWithChildren
behind the scenes, so we don't have to worry about connecting our Props
with it:import React from 'react';
export interface Props {
heading: string;
}
const PostPreview: React.FC<Props> = (props) => {
return (
<div>
<h1>{props.heading}</h1>
{props.children}
</div>
);
};
export default PostPreview;
React.FC
, the TypeScript compiler now knows that our PostPreview
constant is a React component. We no longer have to think about importing React ourselves, as the compiler already prompts us to do so. However, the compiler still does not know how our component looks like in detail. It cannot tell whether it is a <div>
element or a <p>
element or something else. Hence we come to solution number three.React.HTMLProps
. The HTMLProps
support a variety of tags (HTMLDivElement
, HTMLFormElement
, HTMLInputElement
, etc.). Make sure that the type variable matches the outmost tag (the first tag, that is mentioned after return
):import React from 'react';
export interface Props extends React.HTMLProps<HTMLDivElement> {
heading: string;
}
const PostPreview = (props: Props) => {
return (
<div>
<h1>{props.heading}</h1>
{props.children}
</div>
);
};
export default PostPreview;
<div>
element and extends them with custom props like heading
. PostPreview
component can now be used as follows:import React from 'react';
import PostPreview from './PostPreview';
const IndexPage: React.FC = () => {
return (
<div>
<PostPreview heading="First Post">
<p>#1</p>
</PostPreview>
<PostPreview heading="Second Post">
<p>#2</p>
</PostPreview>
</div>
);
};
export default IndexPage;