Search code examples
reactjsclassconstructorsuper

Can we call constructor(props) with other names in react?


constructor(props) {
  super(props);

Learning react, I always come across those two lines. I understand that the super must be written in order to use the "this" method. But why do we always use the word "props"? What if our class holds information about people and we want to pass : (Age, Name, Job)? Is the following code valid?

constructor(Age, Name, Job) {
super(Age, Name, Job);

If not, what does "props" trigger inside of React.Component?


Solution

  • The React Component class expects 3 argument to its constructor: props, context and updater.

    You could do

    constructor(Age, Name, Job) {
      super(Age, Name, Job);
    

    but you have to keep in mind that you are just renaming props, context and updater here, and it doesn't do anything special.

    When you are passing props like

    <MyComponent age={age} name={name} />
    

    They are available as properties of props. In the constructor, you would access them like this:

    constructor(props){ 
      super(props);
    
      console.log('age', props.age);
      console.log('name', props.name);
    }