Getting Started with React and TypeScript
This tutorial will guide you through setting up a new React project using TypeScript, covering essential concepts and best practices.
1. Project Setup
We'll use Create React App (CRA) with the TypeScript template to quickly bootstrap our project.
Step 1.1: Create a New React App
Open your terminal or command prompt and run the following command:
npx create-react-app my-react-ts-app --template typescript
This will create a new directory named my-react-ts-app
with a basic React project configured for TypeScript.
Step 1.2: Navigate to the Project Directory
Change into the newly created project directory:
cd my-react-ts-app
Step 1.3: Start the Development Server
Run the following command to start the development server:
npm start
This will open your new React application in your default web browser at http://localhost:3000
.
2. Understanding TypeScript in React
TypeScript brings static typing to JavaScript, enhancing code quality, maintainability, and developer productivity.
Key Concepts:
- Types: Define the shape of your data (e.g.,
string
,number
,boolean
,object
,array
). - Interfaces: Define custom object structures.
- Components: React components are typed using
React.FC
(Functional Component) or class component types. - Props: Define the types for the properties passed to your components.
- State: Type your component's state using
useState<Type>
.
3. Creating a Typed Component
Let's create a simple component with typed props and state.
Step 3.1: Define Prop Types
Create a new file named components/Greeting.tsx
and add the following code:
import React from 'react';
interface GreetingProps {
name: string;
messageCount?: number;
}
const Greeting: React.FC<GreetingProps> = ({ name, messageCount = 0 }) => {
return (
<div>
<h2>Hello, {name}!</h2>
{messageCount > 0 && <p>You have {messageCount} unread messages.</p>}
</div>
);
};
export default Greeting;
Step 3.2: Use the Typed Component
Now, update your src/App.tsx
file to use the Greeting
component:
import React from 'react';
import './App.css';
import Greeting from './components/Greeting'; // Assuming Greeting.tsx is in a 'components' folder
function App() {
return (
<div className="App">
<header className="App-header">
<Greeting name="Alice" messageCount={5} />
<Greeting name="Bob" />
</header>
</div>
);
}
export default App;
4. Typing Component State
Let's add some local state to a component using the useState
hook.
Step 4.1: Create a Counter Component
Create a new file named components/Counter.tsx
:
import React, { useState } from 'react';
const Counter: React.FC = () => {
const [count, setCount] = useState<number>(0); // Explicitly type the state
return (
<div>
<h3>Counter Example</h3>
<p>Current count: {count}</p>
<button onClick={() => setCount(prevCount => prevCount + 1)}>
Increment
</button>
<button onClick={() => setCount(prevCount => prevCount - 1)} style={{ marginLeft: '10px' }}>
Decrement
</button>
</div>
);
};
export default Counter;
Step 4.2: Add to App Component
Include the Counter
component in your src/App.tsx
:
import React from 'react';
import './App.css';
import Greeting from './components/Greeting';
import Counter from './components/Counter'; // Import Counter
function App() {
return (
<div className="App">
<header className="App-header">
<Greeting name="Alice" messageCount={5} />
<Greeting name="Bob" />
<hr style={{ width: '80%', margin: '30px 0', borderColor: '#e0e0e0' }} />
<Counter />
</header>
</div>
);
}
export default App;
5. Further Learning
This tutorial covered the basics. For more advanced topics, explore:
- Context API with TypeScript: Learn how to type React's Context API.
- Redux with TypeScript: Integrate Redux with proper type definitions.
- Custom Hooks: Create and type your own reusable logic.
- Styled Components/Emotion: Use CSS-in-JS libraries with TypeScript.
Consult the official React documentation and TypeScript handbook for more details.