Introduction
Props enable components to have dynamic data, wich makes them even more useful. In this article I will talk about how to implement Props and mention a few example and best practices.
| Overview |
|---|
| About Props |
| Types |
| Reusable Types |
About Props
Props are inputs that are passed down to the component, just like function parameters. Since they are passed down, they are controlled by the parent and should always be treated as readonly. Props can basically be any JavaScript object.
Types
Creating a type for the props, really does increase the readability of the code a lot, enables full type safety and should always be implemented. A simple example of a type can look like that:
type ProjectCardProps = {
project: Project;
};
const AppProjectCard = ({ project }: ProjectCardProps) => {..}Few examples
Ofc there are many different possibilities for props, I will listen below a few of the many option out there:
type Props = {
title?: string;
items: number[];
isActive: boolean;
color: "btn-secondary" | "btn-info";
};Note that for optional props, I can define a default value:
const CustomButton = ({ name = "Verstappen" }: Props) => {
// ...
};Functions
Itβs also possible to pass whole functions as props. These functions can be defined in the parent component and then be passed down to the component.
type Props = {
handleClick: () => void;
handleChange: (value: string) => string;
};Children
Sometimes I might even want to pass a whole component as a prop. This is usually done via the children prop:
import { ReactNode } from "react";
type Props = {
children: ReactNode;
};
function Button({ children }: Props) {
return <button>{children}</button>;
}In other cases, it might be useful to give the children prop another name to make it more specific, what exactly is it expected to be. This often happens if a component has more than only one prop:
type CardCompactProps = {
title: string;
content: React.ReactNode;
};
const CardCompact = ({
title,
content,
}: CardCompactProps) => {
return (
<Card className={className}>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent>{content}</CardContent>
</Card>
);
};
export { CardCompact };
Reusable Types
There might be the case that different components use the same props. In this case itβs definitely smart, to extract the props into itβs own file and just import it where needed.
Conclusion
Props are the one thing that makes components even more useful, with giving them the ability do handle dynamic data or even whole other components as children. Props are super flexible and will probably be used in almost every component I will ever build.