4

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Aaaahh... Coming from Java I was always trying to call super.render() and that didn't work. I guess the trick is on the baseRender function. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.