React with TypeScript : Get Started
How to create a simple project using React with TypeScript
In this article I’d like to explain briefly the pros of using React with TypeScript and how to create a simple project with the same.
Before starting with React, ensure that the prerequisites, Node.js and npm, are installed.
Why React with TypeScript?
React is a JavaScript library for building user interfaces. As a developer, you can choose to configure either JavaScript or TypeScript.
Since TypeScript is the super set of JavaScript and has static typing, it is less error prone.
Initialization
In order to create a React app, we can use Create React App, a utility that helps to create skeleton structure of a React app.
Create React App by default generates an app with JavaScript. But if you want to use TypeScript with React, you have to enable TypeScript separately.
To create a new project with TypeScript support, run the following command on your workspace directory:
A React app with the name my-app is created and app is enabled to use TypeScript. TypeScript and all related dependencies are configured by default in package.json file as follows:
We can also see other default configuration settings generated by Create React App in tsconfig.json file.
Run
Now start the development server by entering following command:
Your React-Typescript app would start successfully. It can be accessed via URL http://localhost:3000
Customization
Before proceeding with further development, you can do the following optional clean-up activities as well.
- Remove logo.svg file and its import statements from App.tsx (or replace it with another relevant logo).
- Clear everything inside div in App.tsx and add new sections.
- Create ‘components’ directory in src directory to keep your own components.
- Create a directory named App under components folder and move everything related to App to that folder.
Now the folder structure is pretty clean. Continue coding :)
Happy hacking.