Home > Enterprise >  Typescript in React Native
Typescript in React Native

Time:09-22

I have the following codes on my App.tsx file:

import React from 'react';
import {StyleSheet, View, SafeAreaView, Text} from 'react-native';

export interface Props {
  totalCount: number;
  readingCount: number;
  doneCount: number;
}

interface State {
  totalCount: number;
  readingCount: number;
  doneCount: number;
}

export default class App extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);

    this.state = {
      totalCount: 0,
      readingCount: 0,
      doneCount: 0,
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <SafeAreaView />
        <View style={styles.headerContainer}>
          <Text style={styles.headerTitle}>Book Worm</Text>
        </View>
        <View style={styles.bodyContainer}>
          <Text>Body</Text>
        </View>
        <View style={styles.footerContainer}>
          <View style={styles.menuContent}>
            <Text>Book List</Text>
            <Text>{this.state.totalCount}</Text>
          </View>
          <View style={styles.menuContent}>
            <Text>Reading</Text>
            <Text>{this.state.readingCount}</Text>
          </View>
          <View style={styles.menuContent}>
            <Text>Done</Text>
            <Text>{this.state.doneCount}</Text>
          </View>
        </View>
        <SafeAreaView />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  headerContainer: {
    borderBottomWidth: 1,
    borderColor: 'black',
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerTitle: {
    fontSize: 24,
  },
  bodyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  menuContent: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  footerContainer: {
    flexDirection: 'row',
    borderTopWidth: 1,
    borderColor: 'black',
    height: 50,
  },
});

Notice that on the top I have export interface Props and interface State.

And then inside mu export default class App I put <Props, State> at the end.

My question is since I only need the state and this class component will not receive any props, can I omit the export interface Props at the top and simple retain the interface State. Then on my export default should look like export default class App extends React.Component<State> { without the word "Props".

I tried removing it, but its being required inside the constructor like this:

 constructor(props: Props) {
    super(props);

    this.state = {
      totalCount: 0,
      readingCount: 0,
      doneCount: 0,
    };
  }

Sorry I am new to react native and typescript so I am trying to learn as much as I could using class component only.

CodePudding user response:

You can see the documentation https://reactnative.dev/docs/typescript or TypeScript React State without Props .

  • Related