How to Get Started with React and TypeScript?

Overview

Using React with TypeScript makes React, a popular JavaScript library for building user interfaces, even more powerful. We'll walk you through the steps of setting up your first React application with TypeScript, covering essential topics like project structure and configuration. Let's get started today!

Prerequisites

The following prerequisites must be installed on your system before you can dive into React with TypeScript:

Node.js

For package management and JavaScript execution, Node.js is required.

Npm

JavaScript packages are managed by npm, a Node.js feature.

Create a New React Project

The Create React App tool bootstraps a React project using TypeScript.

npx create-react-app ziggy-rafiq-react-app --template typescript
cd ziggy-rafiq-react-app

Using this command, you will create a new React project named "ziggy-rafiq-react-app" with TypeScript configuration.

Project Structure

TypeScript is used to create a React project, which follows the following structure:

src Folder

The source code for your application is located in the src folder.

public Folder

Static assets such as HTML files and images are stored in the public folder.

package.json

The package.json file defines the dependencies and scripts of the project.

tsconfig.json

The TypeScript configuration file is called tsconfig.json.

Writing Your First TypeScript React Component

 Make the following modifications to the src/App.tsx file:

import React from 'react';

interface AppProps {
  message: string;
}

const App: React.FC<AppProps> = ({ message }) => {
  return (
    <div>
      <h1>{message}</h1>
    </div>
  );
};

export default App;

 Make the following modifications to the src/index.tsx file:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
       <App message="Hello, from Ziggy Rafiq!" />
  </React.StrictMode>
);

reportWebVitals();

 Make the following modifications to the src/App.test.tsx file:

import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
  render(    <App message="Hello, from Ziggy Rafiq!" />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

 The code example above shows how you can create a functional React component using TypeScript. It receives a string-type prop message.

Running Your React App

Run your React application by running the following commands below.

npm start

Take a look at your TypeScript React application at http://localhost:3000.

TypeScript Configuration

TypeScript configuration is explained in the tsconfig.json file. Adjust compiler options according to your project needs.


{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "declaration": true,
    "rootDir": "src",
    "outDir": "build"
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.json"],
  "exclude": ["node_modules"]
}

Summary

Your React project with TypeScript has been successfully set up! From here, you can explore more advanced concepts, integrate state management libraries, and enhance your application with additional features. This guide provides a foundation for building React applications using TypeScript. For further insights and best practices, refer to the official documentation and community resources as you continue your React and TypeScript journey.

Please do not forget to like this article if you have found it useful and follow me on my LinkedIn https://www.linkedin.com/in/ziggyrafiq/. also, I have uploaded the source code for this article on my GitHub Repo:   https://github.com/ziggyrafiq/react-typescript-guide. Recently, I published a book on Amazon, “Understanding C#12 Coding Standards, Best Practices, and Standards in the Industry: Developing Robust and Maintainable Code in Today's Development Environment” recommend you read it as it provides lots of code examples and industry standards and best practices using C# 12. 

Happy coding!


Capgemini
Capgemini is a global leader in consulting, technology services, and digital transformation.