📘
TypeScript with React: Components and Props
Intermediate
120 XP
50 min
Lesson Content
TypeScript with React
TypeScript makes React components more maintainable and less error-prone. Essential for modern React development.
Typed Props
interface ButtonProps {
label: string;
onClick: () => void;
disabled?: boolean;
}
function Button({ label, onClick, disabled }: ButtonProps) {
return (
);
}Typed State
const [count, setCount] = useState(0);
const [user, setUser] = useState(null); Typed Events
function handleChange(event: React.ChangeEvent) {
console.log(event.target.value);
} Generic Hooks
function useLocalStorage(key: string, initialValue: T) {
const [value, setValue] = useState(() => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
return [value, setValue] as [T, typeof setValue];
} Example Code
Practice typing React components (conceptual)
// React TypeScript example (conceptual)
// In real React:
interface UserCardProps {
name: string;
age: number;
email: string;
}
// function UserCard({ name, age, email }: UserCardProps) {
// return <div>{name} ({age}) - {email}</div>;
// }
// For practice, simulate component logic
function formatUser(name: string, age: number, email: string): string {
return `${name} (${age}) - ${email}`;
}
console.log(formatUser("John", 30, "john@example.com"));Expected Output:
John (30) - john@example.com
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code