8) React Project with Typescript
React + TypeScript Project Setup
Using Create React Appnpx create-react-app my-app --template typescriptThis creates,
my-app/ ├── src/ │ ├── App.tsx │ ├── index.tsx │ └── react-app-env.d.ts ├── tsconfig.json └── package.jsonUsing Vite (Recommended Modern Setup)
npm create vite@latest my-app -- --template react-tsInstall dependencies
cd my-app npm install npm run devImportant TypeScript Configuration
tsconfig.json: Main configuration file for TypeScript.{ "compilerOptions": { "target": "ES2020", "lib": ["DOM", "ES2020"], "jsx": "react-jsx", "module": "ESNext", "strict": true, "moduleResolution": "Node", "esModuleInterop": true, "skipLibCheck": true } }File Extensions in React TS
i).ts- TypeScript files
ii).tsx- React JSX + TypeScript
iii).d.ts- Type DeclarationsComponent Typing in React
Component typing defines what a component accepts and returns.
i) Basic Typed Componentfunction Welcome(): JSX.Element { return <h1>Hello</h1>; }ii) Arrow Function Component
const Welcome = (): JSX.Element => { return <h1>Hello</h1>; };Props Typing
Props typing ensures only valid data is passed to components.interface UserProps { name: string; age: number; } const UserCard = ({ name, age }: UserProps) => { return ( <div> <h2>{name}</h2> <p>{age}</p> </div> ); };Optional Props
interface ButtonProps { title: string; disabled?: boolean; }Default Props
interface ButtonProps { title: string; color?: string; } const Button = ({ title, color = "blue" }: ButtonProps) => { return <button>{title}</button>; };Children Props Typing
interface CardProps { children: React.ReactNode; } const Card = ({ children }: CardProps) => { return <div>{children}</div>; };Event Typing
i) Button Click Eventconst handleClick = ( event: React.MouseEvent<HTMLButtonElement> ) => { console.log(event); };ii) Input Change Event
const handleChange = ( event: React.ChangeEvent<HTMLInputElement> ) => { console.log(event.target.value); };State Typing
i) Primitive Stateconst [count, setCount] = useState<number>(0);ii) Object State
interface User { name: string; age: number; } const [user, setUser] = useState<User>({ name: "", age: 0 });iii) Array State Typing
const [users, setUsers] = useState<User[]>([]);iv) useRef Typing
const inputRef = useRef<HTMLInputElement>(null);Generic Components
Reusable typed components.interface ListProps<T> { items: T[]; renderItem: (item: T) => React.ReactNode; } function List<T>({ items, renderItem }: ListProps<T>) { return ( <ul> {items.map((item, index) => ( <li key={index}> {renderItem(item)} </li> ))} </ul> ); }<List items={[1, 2, 3]} renderItem={(item) => <span>{item}</span>} />TypeScript Compilation Flow
TSX Files ↓ TypeScript Compiler (tsc) ↓ JavaScript ↓ Bundler (Vite/Webpack) ↓ Optimized Production Bundle