ElJefeJames ElJefeJames - 2 months ago 10
React JSX Question

Why can't I access default props in react constructor, but I can in render?

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?

export default class AboutBox extends TrackerReact(React.Component) {
static defaultProps = {
title: 'Undefined Product',
}
constructor() {
super();
console.log(this.props.title); //this fails
}
render() {
console.log(this.props.title); //this works
return(
<div>
<h1>{this.props.title}</h1>
</div>
)
}
}

Answer

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