Skip to main content

Command Palette

Search for a command to run...

8) React Project with Typescript

Updated
  1. React + TypeScript Project Setup
    Using Create React App

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

    This creates,

    my-app/
     ├── src/
     │    ├── App.tsx
     │    ├── index.tsx
     │    └── react-app-env.d.ts
     ├── tsconfig.json
     └── package.json
    

    Using Vite (Recommended Modern Setup)

    npm create vite@latest my-app -- --template react-ts
    

    Install dependencies

    cd my-app
    npm install
    npm run dev
    
  2. Important 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
      }
    }
    
  3. File Extensions in React TS
    i) .ts - TypeScript files
    ii) .tsx - React JSX + TypeScript
    iii) .d.ts - Type Declarations

  4. Component Typing in React
    Component typing defines what a component accepts and returns.
    i) Basic Typed Component

    function Welcome(): JSX.Element {
      return <h1>Hello</h1>;
    }
    

    ii) Arrow Function Component

    const Welcome = (): JSX.Element => {
      return <h1>Hello</h1>;
    };
    
  5. 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>
      );
    };
    
  6. Optional Props

    interface ButtonProps {
      title: string;
      disabled?: boolean;
    }
    
  7. Default Props

    interface ButtonProps {
      title: string;
      color?: string;
    }
    
    const Button = ({ title, color = "blue" }: ButtonProps) => {
      return <button>{title}</button>;
    };
    
  8. Children Props Typing

    interface CardProps {
      children: React.ReactNode;
    }
    
    const Card = ({ children }: CardProps) => {
      return <div>{children}</div>;
    };
    
  9. Event Typing
    i) Button Click Event

    const handleClick = (
      event: React.MouseEvent<HTMLButtonElement>
    ) => {
      console.log(event);
    };
    

    ii) Input Change Event

    const handleChange = (
      event: React.ChangeEvent<HTMLInputElement>
    ) => {
      console.log(event.target.value);
    };
    
  10. State Typing
    i) Primitive State

    const [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);
    
  11. 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>}
    />
    
  12. TypeScript Compilation Flow

    TSX Files
       ↓
    TypeScript Compiler (tsc)
       ↓
    JavaScript
       ↓
    Bundler (Vite/Webpack)
       ↓
    Optimized Production Bundle