Destructuring React Props with TypeScript
12 May 2022Pass Props Object
Pass your data object through to the rendering component.
// App.tsx
import Header from "./Header";
...
{dataHeader ? (
<Header dataHeader={dataHeader} />
) : (
<Error message="Component cannot render" />
)}
Destructure Props Object
Create an interface
which defines the nested types.
Then use inline destructuring in the parameters where props are received.
// Header.tsx
import { FC } from "react";
interface Props {
dataHeader: {
id: number;
name: string;
};
}
const Header: FC<Props> = ({
dataHeader: { id, name },
}) => {
return (
<header>
<h1>
{id} : {name}
</h1>
</header>
);
};
export default Header;
References
https://github.com/typescript-cheatsheets/react
https://linguinecode.com/post/destructure-react-component-prop-object