0

Props pass to constructor of a class is for ? Since I can get my props using this.props.something, why I still seeing some people pass the props to the constructor? more confusingly it's passed to the super(props).

class Todo extends React.Component {
  constructor(){
    super()
    this.data = ['write book','wash clothes','jogging'];
  }
  render() {
    return (      
      <div>
        <ul>
         {this.data.map((item)=><TodoItem key={item} item={item}/>)}
        </ul>
      </div>
    );
  }
}

class TodoItem extends React.Component {
  constructor(props){
    super(props); // what is this for here?
  }
  render(){
    return(

      <li>
        <span>{this.props.item}</span>
      </li>
    )
  }
}

ReactDOM.render(
  <Todo/>,
  document.getElementById('react_example')
);
<div id="react_example"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Jay
  • 165
  • 1
  • 9
  • I've converted your example into a **runnable** snippet; next time, you can do it: http://meta.stackoverflow.com/questions/338537/how-do-i-create-a-reactjs-stack-snippet-with-jsx-support – T.J. Crowder Jan 09 '17 at 13:02
  • Wouldn't your question/example make more sense if you removed `props` from `TodoItem`'s `constructor` parameter list and didn't pass it to `super`? – T.J. Crowder Jan 09 '17 at 13:02
  • You might find reading [this](http://stackoverflow.com/questions/30571875/whats-the-difference-between-super-and-superprops-in-react-when-using-e) helpful. – Hardik Modha Jan 09 '17 at 13:04
  • You may want to understand more how object oriented programming works. When you instantiate a class, you can pass properties. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes – Nick Salloum Jan 09 '17 at 13:06

0 Answers0