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:
- Setting up a React project with TypeScript.
- Basic TypeScript concepts in the context of React.
- Typing React components and props.
- Using TypeScript with React hooks.
- 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.
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:
-
Install TypeScript and necessary types:
npm install typescript @types/react @types/react-dom
-
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"] }
-
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.
- Define the props and state types.
- Create a form with username and password fields.
- 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
- What is React?
- Setting Up the Development Environment
- Hello World in React
- JSX: JavaScript Syntax Extension
Module 2: React Components
- Understanding Components
- Functional vs Class Components
- Props: Passing Data to Components
- State: Managing Component State
Module 3: Working with Events
Module 4: Advanced Component Concepts
- Lifting State Up
- Composition vs Inheritance
- React Lifecycle Methods
- Hooks: Introduction and Basic Usage
Module 5: React Hooks
Module 6: Routing in React
Module 7: State Management
- Introduction to State Management
- Context API
- Redux: Introduction and Setup
- Redux: Actions and Reducers
- Redux: Connecting to React
Module 8: Performance Optimization
- React Performance Optimization Techniques
- Memoization with React.memo
- useMemo and useCallback Hooks
- Code Splitting and Lazy Loading
Module 9: Testing in React
- Introduction to Testing
- Unit Testing with Jest
- Testing Components with React Testing Library
- End-to-End Testing with Cypress
Module 10: Advanced Topics
- Server-Side Rendering (SSR) with Next.js
- Static Site Generation (SSG) with Next.js
- TypeScript with React
- React Native: Building Mobile Apps