TypeScript with React & Next.js
Build bulletproof React components by typing component props, hooks, event handlers, and state management.
1. Typing Component Props
import React from 'react';
// Define component Props interface
interface ButtonProps {
label: string;
onClick: () => void;
variant?: 'primary' | 'secondary' | 'danger';
disabled?: boolean;
}
export const CustomButton: React.FC<ButtonProps> = ({
label,
onClick,
variant = 'primary',
disabled = false
}) => {
return (
<button onClick={onClick} disabled={disabled} className={`btn btn-${variant}`}>
{label}
</button>
);
};2. Typing Hooks (`useState` & `useRef`)
import { useState, useRef } from 'react';
interface User { id: number; username: string }
export function UserProfileComponent() {
// useState with explicit generics or null union
const [user, setUser] = useState<User | null>(null);
// useRef DOM element binding
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
inputRef.current?.focus();
};
}3. Typing Form & Input Events
import React, { useState, ChangeEvent, FormEvent } from 'react';
export function ContactForm() {
const [email, setEmail] = useState('');
// Typing Input Change Event
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setEmail(e.target.value);
};
// Typing Form Submit Event
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log("Submitted email:", email);
};
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}Next Up
Learn TypeScript with Node.js & Express: typing controllers, request/response, and middleware.
Next Lesson: TypeScript with Node.js & Express →