0

Per the title, why does the initial this.props fail? And more practically, how do you work around this in cases where you rely on the props within your constructor? For instance I would like to reference props within my subscriptions?

class AboutBox extends Component {
  static defaultProps = {
    title: 'Undefined Product',
  }
  constructor() {
    super();
    console.log(this.props.title); //this fails (=> null)
  }
  render() {
    console.log(this.props.title); //this works (=> 'Undefined Product')
    return null;
  }
}
Evgenia Karunus
  • 10,715
  • 5
  • 56
  • 70
ElJefeJames
  • 295
  • 3
  • 16
  • 1
    Related: http://stackoverflow.com/q/30571875/2088135 – Tom Fenech Sep 27 '16 at 11:14
  • Possible duplicate of [What's the difference between "super()" and "super(props)" in React when using es6 classes?](http://stackoverflow.com/questions/30571875/whats-the-difference-between-super-and-superprops-in-react-when-using-e) – Robin Pokorny Apr 06 '17 at 08:08

3 Answers3

5

You have to put the props on the constructor args, and pass them to super

constructor(props){
    super(props);
    console.log(props.title);
}

use props inside constructor, this works also, but have some problem in transpilation against IE

Daniele
  • 1,938
  • 16
  • 24
1

Try adding props to the constructor() parameters and to the super() call:

constructor(props) {
  super(props);
  console.log(props.title);
}
Piotr Berebecki
  • 7,428
  • 4
  • 33
  • 42
0

If you want to use this.props in the constructor, you need to pass props to super(). Otherwise, it doesn't matter because React sets .props on the instance from the outside immediately after calling the constructor.

Chang
  • 1,658
  • 1
  • 17
  • 23