Getting Started with React TypeScript
React (or React.js) is a JavaScript library designed to help developers build dynamic and interactive user interfaces, especially for single-page applications (SPAs). It was developed by Facebook and is widely used for creating reusable UI components that update efficiently based on changes in the application’s data. (https://blog.hubspot.com/website/react-js)
If you don't have Node.js installed, download it from Node.js. You can verify if you have Node and npm installed by running:
node -v
npm -v
2. Create a New React App with TypeScript
Use the following command to create a new React app using TypeScript:
npx create-react-app react-getting-started --template typescript
cd react-getting-started
This sets up a React project with TypeScript.
3. Start the Development Server
Navigate to the project directory and start the development server:
npm start
This will open the app in your browser at http://localhost:3000
.
4. Project Structure with TypeScript
The project structure will look similar to a regular React app, with the main difference being the use of .ts
and .tsx
files instead of .js
:
react-getting-started
├── node_modules
├── public
│ ├── index.html
│ └── ...
├── src
│ ├── App.css
│ ├── App.tsx
│ ├── index.tsx
│ └── ...
├── tsconfig.json
├── package.json
└── ...
tsconfig.json
: This file contains the configuration for TypeScript.src/index.tsx
: The main entry point for your app.src/App.tsx
: Your main React component in TypeScript.
5. Basic Example with TypeScript
Open src/App.tsx
and modify it to include TypeScript types:
import React from 'react';
interface AppProps {
message: string;
}
const App: React.FC<AppProps> = ({ message }) => {
return (
<div>
<h1>{message}</h1>
<p>Welcome to your first React app with TypeScript.</p>
</div>
);
};
export default App;
In this example:
AppProps
is an interface that defines the props that the component accepts (message
of typestring
).React.FC
is the type for functional components.
To use this component, modify src/index.tsx
:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App message="Hello, React with TypeScript!" />
</React.StrictMode>,
document.getElementById('root')
);
6. Working with Types
When using TypeScript with React, you'll often work with interfaces or types to define the structure of your components' props, state, and more. For example:
Props: Define the data that components expect.
State: Define the internal state of a component.