C

Components & Props

Type-safe React components with properly typed props, children, and default values.

Code

typescript
1import React from "react";
2
3// Basic props interface
4interface ButtonProps {
5 label: string;
6 onClick: () => void;
7 variant?: "primary" | "secondary" | "danger";
8 disabled?: boolean;
9}
10
11// Functional component with typed props
12const Button: React.FC<ButtonProps> = ({
13 label,
14 onClick,
15 variant = "primary",
16 disabled = false,
17}) => {
18 const baseStyles = "px-4 py-2 rounded font-medium";
19 const variantStyles = {
20 primary: "bg-blue-500 text-white",
21 secondary: "bg-gray-200 text-gray-800",
22 danger: "bg-red-500 text-white",
23 };
24
25 return (
26 <button
27 className={`${baseStyles} ${variantStyles[variant]}`}
28 onClick={onClick}
29 disabled={disabled}
30 >
31 {label}
32 </button>
33 );
34};
35
36// Props with children
37interface CardProps {
38 title: string;
39 children: React.ReactNode;
40 footer?: React.ReactNode;
41}
42
43const Card: React.FC<CardProps> = ({ title, children, footer }) => (
44 <div className="border rounded-lg shadow-sm">
45 <div className="p-4 border-b font-semibold">{title}</div>
46 <div className="p-4">{children}</div>
47 {footer && <div className="p-4 border-t bg-gray-50">{footer}</div>}
48 </div>
49);
50
51// Generic component props
52interface ListProps<T> {
53 items: T[];
54 renderItem: (item: T, index: number) => React.ReactNode;
55 keyExtractor: (item: T) => string;
56}
57
58function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
59 return (
60 <ul>
61 {items.map((item, index) => (
62 <li key={keyExtractor(item)}>{renderItem(item, index)}</li>
63 ))}
64 </ul>
65 );
66}
67
68// Usage
69const App = () => (
70 <div>
71 <Button label="Click me" onClick={() => console.log("Clicked!")} />
72 <Card title="Welcome">
73 <p>This is the card content.</p>
74 </Card>
75 <List
76 items={[{ id: "1", name: "Alice" }, { id: "2", name: "Bob" }]}
77 renderItem={(user) => <span>{user.name}</span>}
78 keyExtractor={(user) => user.id}
79 />
80 </div>
81);

Run this example locally

$ npx create-react-app my-app --template typescript