Getting Started with Typescript in React
Requirements:
- CLI command execution knowledge is required.
- Node.js and npm were already installed on your computer.
- Install XCode or Android Studio on your computer.
- JavaScript knowledge is required.
- React knowledge is required.
- Some knowledge of React Native is also required (suggested, not required).
npx react-native init CodingNinjas --template react-native-template-typescript
The command above will create a new React Native project with the appropriate dependencies and configurations in a folder called CodingNinjas, using a TypeScript template.
Initializing
You'll be ready to start adding TypeScript once you've tried building a typical React Native app. Let's get started on it.
react-native init CodingNinjas
cd CodingNinjas
Also see, React Native Reanimated
Adding TypeScript
The following step is to integrate TypeScript into your project. The commands below will:
- The typeScript should be used in your project.
- React Native TypeScript Transformer should be included in your project.
- Create an empty TypeScript config file for later configuration.
- And adds typings for React and React Native to an empty React Native TypeScript Transformer config file, which we'll configure next.
- Let's go ahead and test these out.
yarn add --dev typescript
yarn add --dev react-native-typescript-transformer
yarn tsc --init --pretty --jsx react
touch rn-cli.config.js
yarn add --dev @types/react @types/react-native
The tsconfig.json file contains all of the TypeScript compiler's settings. The defaults provided by the program above are acceptable. However, open the file and remove the following line from the comment:
{
/* Search the config file for following line and uncomment it. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
}
The settings for the React Native TypeScript Transformer are in rn-cli.config.js. Open it up and paste the following code into it:
module.exports = {
getTransformModulePath() {
return require.resolve('react-native-typescript-transformer');
},
getSourceExts() {
return ['ts', 'tsx'];
}
};
Migration to TypeScript
The produced App.js, and __tests /App.js files should be renamed App.tsx. index.js must include the .js extension. The .tsx extension (or.ts if the file doesn't include any JSX) should be used for all new files.
You'd get an error saying object prototype may only be an object or null if you tried to start the app right now. This is due to failing to import both the default and named exports from React on the same line. Open the App.tsx and make the following changes to the import at the top of the file:
-import React, { Component } from 'react';
+import React from 'react'
+import { Component } from 'react';
Part of this is due to variations in the way Babel and TypeScript interact with CommonJS modules. The two will eventually settle into the same pattern.
You should now be able to start the React Native application.
Adding TypeScript Testing Features
yarn add --dev ts-jest
Because React Native comes with Jest, we'll need to add ts-jest to our devDependencies to test a React Native app with TypeScript.
Now, We'll have a look at our package. Replace the jest field in JSON with the following:
{
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
"\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/"
],
"cacheDirectory": ".jest/cache"
}
}
This will configure Jest to run .ts and .tsx files with ts-jest.
Adding a Component
Let's add a new feature to our app. Let's start by making a Hello.tsx component. It's a pedagogical component, not anything you'd develop in an app, but something interesting that demonstrates TypeScript with React Native.
Create the components directory and add the following example
import React from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';
export interface Props {
name: string;
enthusiasmLevel?: number;
}
interface State {
enthusiasmLevel: number;
}
export class Hello extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
if ((props.enthusiasmLevel || 0) <= 0) {
throw new Error(
'You could be a little more enthusiastic. :D'
);
}
this.state = {
enthusiasmLevel: props.enthusiasmLevel || 1
};
}
onIncrement = () =>
this.setState({
enthusiasmLevel: this.state.enthusiasmLevel + 1
});
onDecrement = () =>
this.setState({
enthusiasmLevel: this.state.enthusiasmLevel - 1
});
getExclamationMarks = (numChars: number) =>
Array(numChars + 1).join('!');
render() {
return (
<View style={styles.root}>
<Text style={styles.greeting}>
Hello{' '}
{this.props.name +
this.getExclamationMarks(this.state.enthusiasmLevel)}
</Text>
<View style={styles.buttons}>
<View style={styles.button}>
<Button
title="-"
onPress={this.onDecrement}
accessibilityLabel="decrement"
color="red"
/>
</View>
<View style={styles.button}>
<Button
title="+"
onPress={this.onIncrement}
accessibilityLabel="increment"
color="blue"
/>
</View>
</View>
</View>
);
}
}
// styles
const styles = StyleSheet.create({
root: {
alignItems: 'center',
alignSelf: 'center'
},
buttons: {
flexDirection: 'row',
minHeight: 70,
alignItems: 'stretch',
alignSelf: 'center',
borderWidth: 5
},
button: {
flex: 1,
paddingVertical: 0
},
greeting: {
color: '#999',
fontWeight: 'bold'
}
});
Let's take a closer look:
- We're rendering components like View and Button instead of HTML elements like div, span, and h1. These are native components that can be used on multiple platforms.
- The StyleSheet is used to specify styling.
- Develop functionality provided by React Native. React's stylesheets allow us to use Flexbox to control our layout and style with other CSS-like features.
Adding a Component Test
Now that we've got a component let's try testing it.
We already have Jest installed as a test runner. We're going to write snapshot tests for our components. Let's add the required add-on for snapshot tests:
yarn add --dev react-addons-test-utils
Now, in the components directory, make a __tests__ folder and add a test for Hello.tsx:
// components/__tests__/Hello.tsx
import React from 'react';
import renderer from 'react-test-renderer';
import { Hello } from '../Hello';
it('renders correctly with defaults', () => {
const button = renderer
.create(<Hello name="World" enthusiasmLevel={1} />)
.toJSON();
expect(button).toMatchSnapshot();
});
I hope this blog helps you clear all the related concepts of Typescript in React.
Frequently Asked Questions
Is React different from TypeScript?
The sole difference between a TypeScript and a JavaScript React project is that the former's file extension is. tsx, while the latter is Js.
What is the use of TypeScript?
JavaScript code is simplified with TypeScript, making it easier to read and debug. TypeScript is free and open-source software. For the JavaScript IDEs and practices like static checking, TypeScript provides highly productive development tools. TypeScript simplifies the reading and understanding of code.
Define JSX in React?
It's called JSX, and it's a JavaScript syntax extension. It's best to use it alongside React to describe how the UI should look. JSX looks like a template language, but it has all JavaScript's capabilities. React "elements" are created via JSX.
What is TSX in React?
When using the JSX syntax in a React component file, tsx is the extension you should use. The jsx must also be set to true, which is done by default. TypeScript can compile JSX into JavaScript directly.
Conclusion
In this article, we have extensively discussed Typescript in React and how we integrate it into an ongoing project, also discussed the various addons as features in Typescript.
To read more about React and its features, you can refer to ReactJS, Archives, ReactJs and Frontend.
Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses, refer to the mock test and problems; look at the interview experiences and interview bundle for placement preparations.
Do upvote our blogs to help other ninjas grow.
Happy Learning!