nikotromus nikotromus - 22 days ago 6
React JSX Question

Trying to rewrite App.js as a class

I am trying to re-write the entry point App.js javascript file as a class. I'm doing this because I want to call an onClick function when a user clicks on the log out link.

Here is the current code:

import React, { PropTypes } from 'react';
import { IndexLink, Link } from 'react-router';

const App = (props) => {
return (
<div>
<IndexLink className="mypad" to="home">Home</IndexLink>
<Link className="mypad" to="">Log Out</Link>
<br/>
<br/>
{props.children}
</div>
);
};

App.propTypes = {
children: PropTypes.element
};

export default App;


Here was my attempt at re-writing this as a class. It doesn't work. I get the error: 'ReferenceError: props is not defined'

class App extends React.Component {
constructor(props) {
super(props);
}

render(){
return (
<div>
<IndexLink className="mypad" to="home">Home</IndexLink>
<Link className="mypad" to="">Log Out</Link>
<br/>
<br/>
{props.children}
</div>
);
}
}

App.propTypes = {
children: PropTypes.element
};

export default App;

Answer

You need to do this.props once its a class

  <div>
    <IndexLink className="mypad" to="home">Home</IndexLink>
    <Link className="mypad" to="">Log Out</Link>
    <br/>
    <br/>
    {this.props.children}
  </div>

when you write the component as a function, props gets passed in as an argument. When you do it as a class, props are bound to the instance of the component object.