Ads Top

What Does 'super(props)' Mean In A Class Based React Component

Have you ever seen a React application where some components have this line within the constructor() method?
Many tutorials gloss over this line and do not explain it in great detail. Not that there is much detail, but still, it it worth noting what it is and why it is included.

Depending on your Javascript background, you may already be familiar with what it means. But in a framework dominated world, many developers start out learning frameworks while not understanding the underlying basics of pure javascript. If you are familiar with how class based inheritance works in Javascript, you will probably already be aware of what is happening.

Here is a small sample of what this code would look like
What is happening here when we write class App extends React.Component, is that we are extending a class (the base class which is React.component class) that has its own constructor. The class we are extending, has its own setup constructor().

When we do this, we are essentially overriding the constructor of the base class. The problem is, we still want to have all of the setup code within the Component class to run, so in order to do that we add the super(props) line. Everything in this constructor will run, but also, we get all of the benefits of the parent as well.

No comments:

Powered by Blogger.