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!