Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to access props in the constructor?

What is the correct way to access props in the constructor ? Yes i know that in the React documentation is said that

When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs

To be more clear , why do wee need this.props if we can just use props inside constructor

class MyComponent extends React.Component {    
    constructor(props) {
        super(props)

        console.log(props)
        // -> { something: 'something', … }
        // absolutely same
        console.log(this.props)
        // -> { something: 'something', … }
    }
}

Are there some cases when to use props over this.props ?

like image 314
Norayr Ghukasyan Avatar asked Oct 26 '18 07:10

Norayr Ghukasyan


1 Answers

this.props and props are interchangeable in constructor because this.props === props, as long as props is passed to super. The use of this.props allows to detect a mistake instantly:

constructor() {
  super();
  this.state = { foo: this.props.foo }; // this.props is undefined
}

Consistent use of this.props makes it easier to refactor constructor body:

constructor(props) {
  super(props);
  this.state = { foo: this.props.foo };
}

to

state = { foo: this.props.foo };

Only this. needs to be removed.

There are also typing problems with props in TypeScript, this makes this.props preferable for typed component.

like image 163
Estus Flask Avatar answered Oct 22 '22 09:10

Estus Flask