Introduction

TypeScript is a statically typed superset of JavaScript that adds optional types, interfaces, and other features to JavaScript. Using TypeScript with React can help catch errors early, improve code readability, and provide better tooling support.

In this section, we will cover:

  1. Setting up a React project with TypeScript.
  2. Basic TypeScript concepts in the context of React.
  3. Typing React components and props.
  4. Using TypeScript with React hooks.
  5. Practical examples and exercises.

Setting Up a React Project with TypeScript

Using Create React App

The easiest way to set up a React project with TypeScript is by using Create React App (CRA). CRA provides a template for TypeScript, which simplifies the setup process.

npx create-react-app my-app --template typescript
cd my-app
npm start

This command will create a new React project with TypeScript configured. You will see .ts and .tsx files instead of .js and .jsx.

Manual Setup

If you prefer to add TypeScript to an existing React project, follow these steps:

  1. Install TypeScript and necessary types:

    npm install typescript @types/react @types/react-dom
    
  2. Add a tsconfig.json file:

    {
      "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react-jsx"
      },
      "include": ["src"]
    }
    
  3. Rename files:

    Rename your .js and .jsx files to .ts and .tsx respectively.

Basic TypeScript Concepts in React

Types and Interfaces

TypeScript allows you to define types and interfaces to describe the shape of objects.

type User = {
  id: number;
  name: string;
};

interface Product {
  id: number;
  name: string;
  price: number;
}

Typing React Components

Functional Components

You can type functional components using React.FC (Function Component).

import React from 'react';

type GreetingProps = {
  name: string;
};

const Greeting: React.FC<GreetingProps> = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

export default Greeting;

Class Components

Class components can be typed by extending React.Component.

import React, { Component } from 'react';

type CounterProps = {
  initialCount: number;
};

type CounterState = {
  count: number;
};

class Counter extends Component<CounterProps, CounterState> {
  state: CounterState = {
    count: this.props.initialCount,
  };

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

export default Counter;

Using TypeScript with React Hooks

useState

The useState hook can be typed by providing a type argument.

import React, { useState } from 'react';

const Counter: React.FC = () => {
  const [count, setCount] = useState<number>(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Counter;

useEffect

The useEffect hook does not require special typing, but you can type any variables or functions used within it.

import React, { useEffect, useState } from 'react';

const DataFetcher: React.FC = () => {
  const [data, setData] = useState<string | null>(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return <div>{data ? data : 'Loading...'}</div>;
};

export default DataFetcher;

Practical Examples and Exercises

Example: Typing Props and State

Create a TodoList component that accepts an array of todos and displays them.

import React from 'react';

type Todo = {
  id: number;
  text: string;
  completed: boolean;
};

type TodoListProps = {
  todos: Todo[];
};

const TodoList: React.FC<TodoListProps> = ({ todos }) => {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>
          {todo.text} {todo.completed ? '(Completed)' : ''}
        </li>
      ))}
    </ul>
  );
};

export default TodoList;

Exercise: Create a Typed Form Component

Create a LoginForm component with typed props and state.

  1. Define the props and state types.
  2. Create a form with username and password fields.
  3. Handle form submission and display the entered data.

Solution

import React, { useState } from 'react';

type LoginFormProps = {
  onSubmit: (username: string, password: string) => void;
};

const LoginForm: React.FC<LoginFormProps> = ({ onSubmit }) => {
  const [username, setUsername] = useState<string>('');
  const [password, setPassword] = useState<string>('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(username, password);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          Username:
          <input
            type="text"
            value={username}
            onChange={e => setUsername(e.target.value)}
          />
        </label>
      </div>
      <div>
        <label>
          Password:
          <input
            type="password"
            value={password}
            onChange={e => setPassword(e.target.value)}
          />
        </label>
      </div>
      <button type="submit">Login</button>
    </form>
  );
};

export default LoginForm;

Conclusion

In this section, we covered the basics of using TypeScript with React, including setting up a project, typing components, and using hooks. TypeScript can significantly improve the development experience by providing type safety and better tooling support.

Next, we will explore more advanced topics in React, such as server-side rendering and static site generation with Next.js.

React Course

Module 1: Introduction to React

Module 2: React Components

Module 3: Working with Events

Module 4: Advanced Component Concepts

Module 5: React Hooks

Module 6: Routing in React

Module 7: State Management

Module 8: Performance Optimization

Module 9: Testing in React

Module 10: Advanced Topics

Module 11: Project: Building a Complete Application

© Copyright 2024. All rights reserved