6

I've been migrating one of my apps to ES6 on node/react and I have a question about how props are passed down to children. I read a bunch of posts and some address this while others don't. Basically, what I've seen so far is this:

export default class SomeComponent extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>
               {this.props.text} <<< Props used here
            </div>
        );
    }
}

but I've been able to get my component to work with the following:

export default class SomeComponent extends React.Component {
    constructor() {
        super(); <<< notice no props in parentheses 
    }
    render() {
        return (
            <div>
               {this.props.text} <<< Props used here
            </div>
        );
    }
}

is there a reason why I should pass the props in the parentheses for my constructor and the super call? or can I leave my code the way it is

Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127

2 Answers2

1

You don't need to pass props to super unless you want to use this.props in constructor.

https://stackoverflow.com/a/34995257/3238350

zarcode
  • 2,465
  • 17
  • 31
0

You have to pass the props because you are extending from React.Component, otherwise you won't be allowed to access to this.props in the constructor.

It's some kind of composition pattern.

QoP
  • 27,388
  • 16
  • 74
  • 74
  • but it does work, I'm running it right now and its working – Abdul Ahmad Apr 26 '16 at 15:39
  • 3
    well I guess that its not necessary unless you need to use this.props in the constructor, for example, to set an initial state – QoP Apr 26 '16 at 15:42
  • 1
    You don't have to use constructor at all if you don't do anything in it. Even if you want to set initial state it's much less boilerplate if you use `componentWillMount() { this.setState({}) }` – Foxhoundn Apr 26 '16 at 15:50