0

I am in the process of learning React.js and would like to better understand class-based Components; specifically the constructor method (if it is a method). I am coming from Python and I believe it is a little different than the classes there. Is the __init__ method in Python the same as the constructor in React?

During a recent course I followed along on the course dev wrote a Component for users registering. This Component does not call the constructor method, but rather initializes state inside the class. It looks like this:

class Register extends Component {

    state = {
        username: "",
        phone: "",
        email: "",
        password: "",
        password2: "",
        smsNotifications: true,
        emailNotifications: true,
    }
    onChange = e => {
        this.setState({
            [e.target.name]: e.target.value
        });
    }

Now, looking at the React docs it says:

If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component."

Why is the constructor not used in this instance? How can I identify when a constructor needs to be used? It seems from looking at the docs that the constructor should almost always be used.

Thanks for the help!

David Alford
  • 2,044
  • 3
  • 12
  • 35
  • 1
    It really *should* say, "If you don't initialize state ***from props*** and you don't bind methods, ...". If you are only setting initial state you don't need to specify a constructor, and using arrow functions "automagically" binds `this` to them, so again, the constructor is unnecessary. – Drew Reese Apr 10 '21 at 01:07
  • That makes a lot more sense. – David Alford Apr 10 '21 at 01:07
  • 1
    "*Is the `__init__` method in Python the same as the `constructor` in React?*" - it's the same as the `constructor` in JavaScript, yes. "*This Component does not have a constructor method, but rather initializes state inside the class*" - notice this works quite different than Python. These are known as "class fields" and are just syntactic sugar for initialising properties inside the constructor, without spelling out the `constructor`. – Bergi Apr 10 '21 at 01:59
  • From what I am reading the transpiler, e.g. Babel, adds the `constructor` later on? – David Alford Apr 10 '21 at 02:03

0 Answers0