3

i'm new in react and i'm notice that we use this.setState() instead of using super.setState() please i need clear explain why we use this to call super class method ?? example :

class Checkbox extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                checked: true
            }
            this.handleCheck = this.handleCheck.bind(this)
        }

        handleCheck() {
            this.setState({
                checked: !this.state.checked
            })
        }

        render() {
            var msg 
            if(this.state.checked) {
                msg = "checked"
            } else {
                msg = "not checked"
            }
            return (
                <div>
                    <input type="checkbox" 
                           onChange={this.handleCheck}
                           defaultChecked={this.state.checked}/>
                    <p>This box is {msg}</p>
                </div>
            )
        }
    }       
Yazan Khateeb
  • 83
  • 2
  • 10
  • 5
    Because it inherits the superclasses methods. – Andrew Li Apr 07 '18 at 16:29
  • so every thing we inherit from super can call them using this? – Yazan Khateeb Apr 07 '18 at 16:31
  • As long as you don't override it by implementing that method in your component (which never really is a problem because you only ever implement your own lifecycle methods which you shouldn't call directly). – Andrew Li Apr 07 '18 at 16:32
  • Inheritance. You only need to use the `super` keyword in a React class constructor to be able to use the `this` keyword in the constructor. You could use it to access methods on the parent class, but there is no need. – Kyle Richardson Apr 07 '18 at 16:39

1 Answers1

3

This is how JavaScript inheritance works. An instance of Checkbox child class prototypically inherits from React.Component parent class, this.setState === super.setState.

super.method should be referred only if it was overridden in child class, it commonly occurs in overridden method itself:

method() {
  super.method(); // inherit the behaviour from parent class
  // do something else
}

Otherwise the use of super.method() can be considered semantic mistake, it shows that a developer wasn't aware of inheritance mechanisms. If a method will be overridden later, it won't be in use because of that (though it's unlikely in case of setState).

The use of super.method() also requires a developer to be aware of parent class implementation. As explained in this answer, only parent prototype methods but not instance methods are available as super. If parent class has instance method,

method = () => {...}

Child class will inherit it as this.method but there will be no super.method.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565