Updated June 7, 2023
Introduction to React Native TypeScript
The following article provides an outline for React Native TypeScript. TypeScript provides us with non-mandatory Interfaces, static typing, and classes. It is very much popular among developers who were earlier working on more structured languages than JavaScript, but now they have started working on JavaScript. TypeScript provides better tools and allows the Integrated Development Environment to provide a better environment that can spot common errors while typing the codes instead of typing the whole code and running it simultaneously. Using TypeScript may result in much better software for creating a large and robust JavaScript project. TypeScript is very good in backward compatibility with the versions of JavaScript.
Working of TypeScript
- When we match the package.json file of any general Project with the package.json file of the Project which uses Typescript, we can see some modules of @types present in the devDependencies.
- These modules work as the Type Declaration Files for the libraries on which we are dependent. So, the types used in the libraries can be easily understood by the Typescript.
- This Transformer is a kind of Babel Transformer that helps transform the .tsx code, enabling it to be easily used in the environment of React Native.
- The Typescript library helps us in using the features of Typescript.
Syntax to Create a React Native Project which uses TypeScript:
react-native init RNTypeScript
--template typescript
&& node RNTypeScript/setup.js
Examples of React Native TypeScript
Here are the examples:
Example #1
Basic Example of using TypeScript in React Native.
In the example below, simple content is displayed in a box inside an Application with different color styling using TypeScript. All the dependencies for building the application are being downloaded from package.json.
The files used to implement the code below are:
a. App.tsx
import * as React from "react";
import { View
, Text
, StyleSheet } from "react-native";
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#84f5ea",
justifyContent: "center",
alignItems: "center"
}
});
function App() {
return (
<View style={styles.container}>
<Text>
<h3>{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}</h3>
<h1>Heyoo</h1>
<h2>Welcome to basic Example of React Native using Typescript</h2>
<h3>{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}{'\u2765'}</h3>
</Text>
</View>
);
}
export default App;
b. index.tsx
import * as React from "react";
import { View
, Text
, StyleSheet
, AppRegistry } from "react-native";
import App from "./App";
const styles = StyleSheet.create({
window: {
margin: 12,
flex: 1,
flexDirection: "column",
borderWidth: 6,
borderStyle: "dotted",
maxWidth: 360,
backgroundColor: "#e32d9a"
},
statusBar: {
height: 38,
paddingHorizontal: 35,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
},
statusBarItem: {
color: "#e8f5b8"
},
app: {
flex: 1,
backgroundColor: "#e994f7"
}
});
const PhoneWindow = (props: any) => (
<View style={styles.window}>
<View style={styles.statusBar}>
<Text style={styles.statusBarItem}>0:00 {'\u2709'}</Text>
<Text style={styles.statusBarItem}>{"4G Airtel 100%"}</Text>
</View>
<View style={styles.app}>
<App />
</View>
</View>
);
const rootTag = document.getElementById("root");
AppRegistry.registerComponent("App", () => PhoneWindow);
AppRegistry.runApplication("App", { rootTag });
c. tsconfig.json
{
"include": [
"./src/*"
],
"compilerOptions": {
"lib": [
"dom",
"es2017"
],
"jsx": "react"
}
}
Output:
Example #2 – Counter
In the example below, we have used TypeScript in the application to develop a counter where the increase button increases the value by 1, and the decrease button decreases the value by 1.
The files used to implement the code below are:
a. index.tsx
import * as React from "react";
import { render } from "react-dom";
interface IState {
count: number;
}
class App extends React.Component<{}, IState> {
public readonly state = {
count: 0
};
private handleClick = (
event: React.MouseEvent<HTMLButtonElement>
) => {
const type: string = event.currentTarget.title;
this.setState(({ count }) => ({
count: type === "decrement" ?
count - 1
: count + 1
}));
};
public render() {
return (
<div>
<h1>Counter using TypeScript in React Native</h1>
<button title="decrement" onClick={this.handleClick}>
Decrease
</button>
{this.state.count}
<button title="increment" onClick={this.handleClick}>
Increase
</button>
<h2>Increase Button Increases value by 1</h2>
<h2>Decrease Button Decreases value by 1</h2>
</div>
);
}
}
render(<App />, document.getElementById("root"));
b. tsconfig.json
{
"compilerOptions": {
"outDir": "build/dist",
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true
},
"exclude": [
"node_modules",
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts"
]
}
Output:
Example #3 – Video Linking
In the example below, we have linked 2 mp4 videos to the application through TypeScript using import videojs from “video.js”; .
Files used to implement the code below are:
a. index.tsx
import * as React from "react";
import { render } from "react-dom";
import VideoPlayer1 from "./video";
import VideoPlayer2 from "./video";
import "./styles.css";
const videoJsOptions1 = {
sources: [
{
src: "https://vod-progressive.akamaized.net/exp=1597215699~acl=%2A%2F1091076383.mp4%2A~hmac=79427f80a30ea33800277ff3ae1acb4a6534099d2a8eede24126830bc8ebf635/vimeo-prod-skyfire-std-us/01/2696/11/288484037/1091076383.mp4?filename=Pexels+Videos+1394254.mp4",
type: "video/mp4"
}
]
};
const videoJsOptions2 = {
sources: [
{
src: "https://vod-progressive.akamaized.net/exp=1597216269~acl=%2A%2F588677125.mp4%2A~hmac=723c7ca3177420e005ffcbfd22667b5f1e2b6eaf1155c735fd1213445dc452c9/vimeo-prod-skyfire-std-us/01/1033/7/180168748/588677125.mp4?filename=Time+Lapse+Video+of+Tall+Buildings.mp4",
type: "video/mp4"
}
]
};
function App() {
return (
<div className="App">
<h1>Welcome to my Video Page</h1>
<h3>Nature Video</h3>
<VideoPlayer1 options={videoJsOptions1} />
<h3>Building Video</h3>
<VideoPlayer2 options={videoJsOptions2} />
</div>
);
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
b. styles.css
.App {
font-family: Cambria
, Cochin
, Georgia
, Times
, 'Times New Roman'
, serif;
text-align: center;
text-decoration-style: dotted;
}
c. video.tsx
import * as React from "react";
import videojs from "video.js";
import "video.js/dist/video-js.css";
interface IVideoPlayerProps {
options: videojs.PlayerOptions;
}
const initialOptions: videojs.PlayerOptions = {
controls: true,
fluid: true,
controlBar: {
volumePanel: {
inline: false
}
}
};
const VideoPlayer: React.FC<IVideoPlayerProps> = ({ options }) => {
const videoNode = React.useRef<HTMLVideoElement>();
const player = React.useRef<videojs.Player>();
React.useEffect(() => {
player.current = videojs(videoNode.current, {
...initialOptions,
...options
}).ready(function() {
});
return () => {
if (player.current) {
player.current.dispose();
}
};
}, [options]);
return <video ref={videoNode} className="video-js" />;
};
export default VideoPlayer;
d. tsconfig.json
{
"include": [
"./src/*"
],
"compilerOptions": {
"lib": [
"dom",
"es2015"
],
"jsx": "react"
}
}
Output:
Recommended Articles
We hope that this EDUCBA information on “React Native TypeScript” was beneficial to you. You can view EDUCBA’s recommended articles for more information.