Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to do inheritance in TypeScript for React components?

Take the following example:

export interface IBaseIconProperties {
    path: string;
}

export default class BaseIcon extends React.Component<IBaseIconProperties, any> {
    public render() {
        return (
            <SvgIcon style={{width: 32, height: 32}}>
                <path d={this.props.path} />
            </SvgIcon>
        );
    }
}

export default class Foo extends React.Component<any, any> {
    public render() {
        return <BaseIcon path="/* SVG path for Foo button goes here... */"/>;
    }
}

export default class Bar extends React.Component<any, any> {
    public render() {
        return <BaseIcon path="/* SVG path for Bar button goes here... */"/>;
    }
}

This is one way one can do inheritance with React components. Not sure if one can call this inheritance though.

But is there another way? A better way? Maybe through actual inheritance where the BaseIcon class is abstract? Is this possible somehow without over complicating things?

like image 512
rfgamaral Avatar asked Oct 23 '25 02:10

rfgamaral


1 Answers

There is nothing wrong with making the base class abstract and extending it from subclasses. Here's what you can do for the example that you gave:

export interface IBaseIconProperties {
        path: string;
    }

export default abstract class BaseIcon extends React.Component<IBaseIconProperties, any> {
        public baseRender(path:String) {
            return (
                <SvgIcon style={{width: 32, height: 32}}>
                    <path d={path} />
                </SvgIcon>
            );
        }

        //put other useful base class methods here
    }

export default Foo extends BaseIcon {
    public render() {
       return this.baseRender("FooPath");
    }
}

export default Bar extends BaseIcon {
    constructor(props: IBaseIconProperties) {
      super(props);
      this.state = {
          //initialize state here, respecting the state type of the base class
      };
    }

    public render() {
       return this.baseRender("BarPath");
    }
}

We do something very similar in our project and it's working quite well (we only have simple cases though).

The downside is that you can't easily declare different state and properties types for subclasses, which may be a limitation.

like image 145
Piotr Sobczyk Avatar answered Oct 24 '25 16:10

Piotr Sobczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!