What’s the Difference Between “Super()” and “Super(props)” in React When Using Es6 Classes?

What’s the difference between “super()” and “super(props)” in React when using ES6 classes?

When working with React and ES6 classes, you might have come across the use of super() and super(props). These two expressions are used to call the constructor of the parent class when extending a component in React. However, there is a subtle difference between them that you should be aware of. Let’s dive in and explore their distinctions.

The “super()” Syntax

When you use super() without passing any arguments, you are simply calling the constructor of the parent class without passing any props. This means that the props object will be undefined within the constructor of the parent class.

Here’s an example:


class ParentComponent extends React.Component {
    constructor() {
        super();
        console.log(this.props); // Output: undefined
    }
}
    

In this case, if you try to access this.props within the constructor of the parent component, it will be undefined.

The “super(props)” Syntax

On the other hand, when you use super(props), you are passing the props object to the constructor of the parent class. This allows you to access the props within the constructor of the parent component.

Here’s an example:


class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        console.log(this.props); // Output: { prop1: 'value1', prop2: 'value2' }
    }
}
    

In this case, this.props will contain the props passed to the child component when it is created.

Which One Should You Use?

The choice between super() and super(props) depends on your specific use case. If you don’t need to access the props within the constructor of the parent component, you can use super(). However, if you need to access the props within the constructor, you should use super(props).

It’s worth noting that if you use super(props), you should also pass the props to the constructor of the child component when calling super(props). This ensures that the props are correctly passed down to the parent component.

Conclusion

In summary, the difference between super() and super(props) lies in whether or not you pass the props object to the constructor of the parent class. By using super(props), you can access the props within the constructor of the parent component. Consider your specific use case and choose the appropriate syntax accordingly.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *