Laizer
Laizer

Reputation: 6150

In React, when inheriting propTypes, how do I avoid duplication?

I'm using an abstract superclass for some React components that share methods and some (but not all) props.

class AbstractStory extends Component { ... }
AbstractStory.propTypes = {
  storyForm: PropTypes.string,
  timestamp: PropTypes.number
}

class NewContentStory extends AbstractStory { ... }

I'm assuming that if the propTypes of the subclass don't differ from the superclass, I can leave them undeclared on the subclass, and they will be inherited from the superclass.

But, if there are additional properties of the subclass, is there a good way to declare them without restating what is declared on the superclass? Is there any issues doing it like this?

NewContentStory.propType = {... AbstractStory, newProp: PropTypes.string}

What about if the subclass modifies a property declared on the superclass (making it required, adding shape to an object, etc.)?

Upvotes: 2

Views: 978

Answers (1)

Webber
Webber

Reputation: 5514

The real answer is that by convention you don't really want to extend components other than React.Component as functional composition is the primary way of abstraction in React.

In other words: You should nest components, rather than extending classes in React.

Upvotes: 2

Related Questions