Arun
Arun

Reputation: 3077

Creating custom components in React Native with TypeScript

I decided to convert my ReactNative project to TypeScript. I'm new to TypeScript and am finding it hard to fix this problem with custom components and inheritance. This is my (scaled down) code

import React, { Component } from "react";
import { Button, View } from "react-native";

interface IMyComponentProps extends React.Props<IMyComponentProps> {
  colWidth?: number;
}

class MyComponent extends Component<IMyComponentProps> {
  getProps() {
    return this.props;
  }
}

class MyButton extends MyComponent {
  render() {
    return (
      <View {...this.getProps()}>
        <Button title={this.props.title} onPress={this.props.onPress} />
      </View>
    );
  }
}

I'm getting a red underline on ...this.getProps() in the MyButton component. Also this.props.title and this.props.onPress are not being identified.

Can you please help me with the types I need to define for these two classes.

Thanks

Upvotes: 2

Views: 3464

Answers (1)

Daniel Rosenwasser
Daniel Rosenwasser

Reputation: 23433

First, you need to declare that a MyButton has more specific props, so MyComponent has to be parameterized:

class MyComponent<P extends IMyComponentProps> extends Component<P> {
  getProps() {
    return this.props
  }
}

Then extend MyComponent correctly and declare its props:

interface IMyButtonProps extends IMyComponentProps {
  colWidth?: number;
  title: string;
  onPress: () => void;
}


class MyButton extends MyComponent<IMyButtonProps> {
  render() {
    return (
      <View {...this.getProps()}>
        <Button title={this.props.title} onPress={this.props.onPress} />
      </View>
    );
  }
}

Then, unless you're using refs, which are hard to reason about, don't extend React.Props. Just declare your interfaces as so:

interface IMyComponentProps {
  colWidth?: number;
}
interface IMyButtonProps extends IMyComponentProps {
  title: string;
  onPress: () => void;
}

Altogether now!

i

mport React, { Component } from "react";
import { Button, View } from "react-native";

interface IMyComponentProps {
  colWidth?: number;
}

class MyComponent<P extends IMyComponentProps> extends Component<P> {
  getProps() {
    return this.props
  }
}

interface IMyButtonProps extends IMyComponentProps {
  title: string;
  onPress: () => void;
}

class MyButton extends MyComponent<IMyButtonProps> {
  render() {
    return (
      <View {...this.getProps()}>
        <Button title={this.props.title} onPress={this.props.onPress} />
      </View>
    );
  }
}

Upvotes: 2

Related Questions