Coding

Create React App with Typescript | Add Typescript to Existing React Project

As of today, React is a viral and one of the greatest front-end libraries; it has become the primary library for many...

Written by Niel Patel · 6 min read >
TypeScript and Create-React-App

As of today, React is a viral and one of the greatest front-end libraries; it has become the primary library for many developers while developing front-end applications.

You’re about to love create-react-app even more

Building a React App with TypeScript

Typescript, on the other hand, is a statically typed programming language that makes our JavaScript code more predictable. One of the key reasons Typescript was invented was to help developers not just create things, but to design products where we can always predict their behavior.

Introduction to create a react app with typescript

Our React applications will be more predictable if we use Typescript to construct them since we will be able to catch a lot of mistakes at runtime (during compilation).

I’ll take you on this journey with me today. I’ll do my best to keep the concepts simple for you. You are not required to code with me. But if you succeed, it will be fantastic!

In this tutorial, I’ll walk you through the steps of creating a simple react application and adding typescript to the existing react project.

This post isn’t intended to be a beginner’s guide to React or Typescript; rather, it will show us how to use Typescript in React apps.

The TypeScript compiler

Starting with the file App.tsx, let’s take a deeper look at the components and tests. The file extension is probably the first thing you noticed. All component files are now tsx instead of jsx, and setupTests.js has been renamed setupTests.ts. But why is that?

Browsers and Node currently don’t accept TypeScript directly; they only comprehend JavaScript, thus we’ll have to transform our TypeScript scripts to JavaScript ones. This is a task that the TypeScript compiler is in charge of.

Different file extensions, such as the ones stated above, are used because the compiler has to know which files to compile vs files that are pure JavaScript.

Adding TypeScript

Note: this feature is available with react-scripts@2.1.0 and higher.

  1. Installation – To start a new Create React App project with TypeScript, you can run the below command.
npx create-react-app my-app --template typescript

# or

yarn create react-app my-app --template typescript

If you’ve previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app or yarn global remove create-react-app to ensure that npx always uses the latest version.

Global installs of create-react-app are no longer supported.

2. Add Typescript to Existing React Project

TypeScript Conversion of an Existing App. Navigate to your app directory in the console, where you’ll want to install TypeScript:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

# or

yarn add typescript @types/node @types/react @types/react-dom @types/jest

Rename any file to be a TypeScript file (e.g. src/index.js to src/index.tsx) and don’t forget to restart the server!

npm install --save typescript @types/node @types/react @types/react-
dom @types/jest

After that, rename any files you want to be TypeScript files to endin.tsx. Instead of App.js, you might use App.tsx.
This is where you might have problems. You’ll see that practically everything in your App.tsx file is marked in red. This isn’t ideal.

If you haven’t already done so, import React from thereact’ section at the beginning of the file.

When you hover over any underlined element in VSCode, the message “Cannot utilize JSX unless the’— jsx’ flag is given” appears. You can either choose the “Quick Correct” option or manually fix it at this point. When you select “Quick Fix,” you’ll be given the option to “Enable the’— jsx’ flag in your configuration file.” It will take a second or two for it to load, and then the errors should be gone.

create react native app typescript

Create React Native App Typescript (Latest Version)

It is not necessary for you to create a tsconfig.json file; one will be created for you. You can make changes to the TypeScript configuration that has been generated.

TypeScript Handbook

Complete Guideline to Creating a Create React Native App Typescript From Scratch

There are two advantages to working within any framework. It improves your skills as a developer and your comprehension of the work you undertake.
It also allows you to appreciate the things that these frameworks perform behind the scenes that we often overlook.
I wanted to dive deep into React to see how an app works behind the scenes by reproducing it locally.

Typescript is a strict and statically typed programming language that improves the predictability of our JavaScript code. One of the key reasons Typescript was invented was to help developers not just create things, but to design products where we can always predict their behavior.

You can use templates to start a new TypeScript app. Append —template typescript to the creation command to utilise our TypeScript template.

npx create-react-app my-app --template typescript

It compiles beautifully with no special settings to enable or packages to download. All the files that would have been .js files are now .ts or .tsx.

add typescript to existing react project

Don’t worry if you’ve already begun working on a project and wish to switch to TypeScript. There is also a solution for it.

Yarn create react app typescript

If you’ve previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app or yarn global remove create-react-app to ensure that npx always uses the latest version.

1. yarn create react app typescript
npx create-react-app my-app --template typescript

# or

yarn create react-app my-app --template typescript


2. how to install react with typescript
npx create-react-app my-app --template typescript

# or
yarn create react-app my-app --template typescript



3. npx react typescript
npx create-react-app my-app --template typescript



4. create-react-app typescript
npx create-react-app my-app --template typescript
# or #
yarn create react-app my-app --template typescriptCopy



5. create react app ts
To create typescript version
npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript

Initialize the Project With Yarn

Then execute the following command to create an npm project (yarn recommended).

yarn init
or
npm init

Here’s What Yarn Output Looks Like

How to Declare Types in React Applications

Let’s create a type for our Todo object, inside the App.tsx file place this object after the import.

type ITodo = { 
  // Our todo should have the title and completed fields and the id field to 
  id: number;
  title: string;
  completed: boolean;
}

type ITodos = {
  todos: ITodo[], // Our Todos is an array of Todo
}

Event types in react

The challenge now is: how can we find out what type was passed to the event?

Well, React has a lot of events, and we can’t possibly know what type each of them has, so I usually place the event object in the handler where it’s being used, hover over it, and copy the type.

<button onClick={e => {console.log(e) }}>Add</button>
(parameter) e: React.MouseEvent<HTMLButtonElement, MouseEvent>

Declaring prop types using ‘React.FC’

const TodosComponent: React.FC<{
  todos: ITodos, 
  toggleTodos: (id: number) => void,
  deleteTodos: (id: number) => void
}> = ({todos, toggleTodos, deleteTodos}) => {
  const deleteTodo = (id: number) => {
    if (window.confirm(`Are you sure you want to delete todo?`)) {
      deleteTodos(id);
    }
  }
  return (
    <div className="section__todos">
    <h2>Todos</h2>
    {todos.todos.length ? <ul className="todos">
      {todos.todos.map(todo => (
        <li key={todo.id}>
          <span style={{textDecoration: todo.completed? 'line-through': 'none'}}>{todo.title}</span>
          <input 
            type="checkbox" 
            checked={todo.completed} 
            onChange={() => toggleTodos(todo.id)} />
          <button onClick={() => {deleteTodo(todo.id)}}>X</button>
        </li>
      ))}
    </ul>: <div>No Todo has been created</div>}
  </div>
  );
};

Typing variables in TypeScript

Let’s take a look at the following example:

let helloWorld = "Hello World";

Because the value in the variable helloWorld is a string, it is now of type string, and you can manipulate it as you normally would with a string. However, if the type of the variable changes in the future, the type of the variable will change as well.

This is how TypeScript works: it assigns a variable’s type based on its value at the time of declaration, therefore the identical line of code will function in both languages. The distinction is based on what happens when you want to assign a new value to a variable of a different type.

We already saw how to do it with JavaScript, but what if we tried the same thing with TypeScript?

Documentation

Here are some of the best places to find up-to-date information on React and TypeScript:

Create react app typescript eslint in 2022

Prerequisites to create react app typescript eslint

Note: You need Node version >= 10 installed. So, if you don’t have it, please go to NodeJS website, download and install it on your local machine. (https://nodejs.org/en/)

Step 1: Create a React Project with Typescript

npx create-react-app my-app --template typescript

Step 2: Remove the pre-set ESLint configuration

“eslintConfig”: {
“extends”:[
“react-app”,
“react-app/jest”
]
}

Step 3: Install ESLint package

npm install eslint --save-dev

Read Next Steps Here

What is a Fibonacci series example

Fibonacci Series Problem in Java

Niel Patel in Coding
  ·   5 min read

Leave a Reply