Introducing React ReExt – Sencha Ext JS Components in React! LEARN MORE

How to Create React App Typescript?

October 6, 2022 2590 Views
Show

React is one of the most popular and effective front-end libraries that uses a component-based approach to build web-based applications. However, Typescript is a stringent and statically typed programming language, which increases the predictability of our JavaScript code. One of the key motivations for the creation of Typescript was to enable developers to create products that are always predictable in terms of their behavior. Applications in React are created with the create react app command. On the other hand, TypeScript creates applications with create react app typescript.

This article will show you the practical side of how to use TypeScript in your React project.

Create React App With TypeScript

Just like setting up a React application with create-react-app, TypeScript applications use create-react-app with a few more options. If you are feeling ambitious, you can read more about the creation of React 16 applications.

npx create-react-app ts-app --template typescript

 

This command will build a react typescript application for us and create a file structure like the one below. You have to be familiar with React JS structures.

File structure created by create react app Typescript

Errors are bound to happen, and if you run into an error here, try to force install the React app.

npx create-react-app@latest my-ts-app --template typescript

 

In case you want to add TypeScript to an existing create React app, use the following command.

For npm

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

For yarn

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

 

Once you add TS, rename any file with a JS file extension (.js) to a TypeScript file extension (.tsx). Additionally, make sure to create a configuration file (tsconfig.json) where you had your package.json file.

A tsconfig.json file would look like the snippet below.

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src/**/*"]
}

 

It’s never a bad idea to check if everything works fine. Restart your development server and IDE. Once done, run the following command to start the app project and spot any errors.

npm start

Typing Props In A React TypeScript Project

TypeScript defines an object/data using Types and Interfaces.

type IProps = {
  disabled: false,
  title: "Hello" | "Hi"
}interface Props {
  disabled: boolean,
  title: string
}const props_types: IProps = {
  disabled: false,
  title: "Hello"
}const props_interface: Props = {
  disabled: false,
  title: "Hello"
}

 

An example of an interface component is below:

import React from 'react';

interface EmployeeProps {
  name?: string; 

  age?: number;
  country: string;
  children?: React.ReactNode;
}

function Employee({name = 'Alice', age = 29, country}: EmployeeProps) {
  return (
    <div>
      <h2>{name}</h2>
      <h2>{age}</h2>
      <h2>{country}</h2>
    </div>
  );
}

export default function App() {
  return (
    <div>
      <Employee country="Austria" />
    </div>
  );
}

 

The above Employee component takes a name, age, country and children props, all definitive under the EmployeeProps interface. But out of those props, if you notice closely, there are question marks on some of them. The ‘?’ indicates that those props are optional. This means you do not have to pass these props to the component, in case you change your mind.

For each of your components that you send props to, you will define a props interface. This states both the object’s shape and the key types that go with it. An interface for the state of class components must also be declared.

Inserting State With The UseState Hook

There are many approaches to declaring a type for the state in a function component, as well as the type for props in a function component. All we need to do is send the type of the state as a generic type to useState to specify a type for the state in a functional component.

import {useState} from 'react';

function App() {

  const [strArr, setStrArr] = useState<string[]>([]);

  const [objArr, setObjArr] = useState<{name: string; age: number}[]>([]);

  setStrArr(['a', 'b', 'c']);

  setObjArr([{name: 'A', age: 1}]);

  return (

    <div className="App">

      <div>Hello world</div>

    </div>

  );

}

export default App;

Typing Events Hook

If you are familiar with React, you might have heard about events. An event wraps up a browser’s event system. In TypeScript, however, you can find events in the @tpes/react npm package.

React has a lot of events, and it’s quite hard to identify every one of them. To find out what event type was passed, you can insert the event object in the handler where it is being used and hover over it before copying the type. This is an inline event.

The render method takes advantage of inline events. A couple of examples include the onClick() and onChange() events.

Following is the code with the event:

const App = () => {

  // onClick event is written inline

  // hover over the `event` parameter with your mouse

  return (

    <div>

      <button onClick={event => console.log(event)}>Click</button>

    </div>

  );

};

export default App;

 

You can find the type of event when you hover over.

But, what next? Since you know the type of event, you can extract the handler function. For instance,

const App = () => {
  const handleClick = (
    event: React.MouseEvent<HTMLButtonElement, MouseEvent>,
  ) => {
    console.log(event.target);
    console.log(event.currentTarget);
  };
  return (
    <div>
      <button onClick={handleClick}>Click</button>
    </div>
  );
};
export default App;

 

Note that TypeScript will be able to determine the type of the event, as long as you write the event handler function inline and hover over the event.

Typing Refs Hook

In React TypeScript, you can type a ref by using the generic on the useRef hook. You can use ref to obtain all of an element’s attributes and methods.

import {useEffect, useRef} from 'react';

export default function App() {

  const inputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {

    inputRef?.current?.focus();

  }, []);

  return (

    <div>

      <input ref={inputRef} />

    </div>

  );

}

 

Because the ref’s default value is null, we utilized the type HTMLInputElement or null when setting the ref on an input element.

In default components, you can see the following import statements.

 

import * as React from 'react';
import * as ReactDOM from 'react-dom';

 

However, React cannot be imported this way. React does not utilize a default export and is exported as a CommonJS module. Knowing the precise reason is not necessary at this stage; all you need to know is how to import React to make it work. Additionally, you must declare your components as class App extends React.

Ready to get started?

This article would have given you an overview of how TypeScript can be integrated with React applications. However, building apps with Sencha is much easier than using TypeScript. Sencha is the most complete front-end framework for creating cross-platform, data-intensive web and mobile applications for any modern device. The addition of Ext JS components to React apps in your project provides you comprehensive React tooling support and easy-to-run integrated applications. Ext JS further comes with more than 140 proven and pre-integrated high-performance UI components. Last but not least, Sencha offers a complete React package for grids with GRUI by Sencha, Webpack, Babel plugins, and Boilerplate examples.

Interested in using Sencha? Start with a 30 day free trial today.

Banner: C-Level Guide for Enterprise Application Development

Frequently Asked Questions (FAQs)

How do I create a React app in TypeScript?

npx create-react-app ts-app –template typescript

Is TypeScript good for React?

Despite the advantages and disadvantages, Typescript still adds a great deal of value to an application. By utilizing TypeScript, you can reduce the number of hours you spend debugging. Therefore, you should use TypeScript in your React project without a doubt.

Is Reactjs TypeScript?

Typescript is a language that builds on Javascript. React, on the other hand, is not a language like TypeScript. Instead, React is a JavaScript library designed to develop user experiences with predictability, power, and efficiency.

Can I use TypeScript with React?

React supports Typescript and also allows you to add Typescript to any of your existing React projects.

Sencha CTA Banner: Try Sencha Ext JS

Recommended Articles

View More