Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Last active July 27, 2016 16:13
Show Gist options
  • Select an option

  • Save remarkablemark/59bc18574a3b383daa1c8f494e6457e4 to your computer and use it in GitHub Desktop.

Select an option

Save remarkablemark/59bc18574a3b383daa1c8f494e6457e4 to your computer and use it in GitHub Desktop.
Creating a React component with `React.createClass` versus `React.Component`.
'use strict';
var React = require('react');
var ReactClass = React.createClass({
displayName: 'ReactClass',
// https://facebook.github.io/react/docs/reusable-components.html#mixins
mixins: [],
propTypes: {
foo: React.PropTypes.string
},
// https://facebook.github.io/react/docs/reusable-components.html#default-prop-values
getDefaultProps: function() {
return {
bar: 42
};
},
getInitialState: function() {
return {
baz: 'qux'
};
},
_handleClick: function() {
console.log(this);
this.setState({
baz: 'clicked'
});
},
render: function() {
return (
<div className={this.state.baz} onClick={this._handleClick}>
Lorem ipsum {this.props.foo} {this.props.bar}
</div>
);
}
});
module.exports = ReactClass;
'use strict';
import React from 'react';
// https://facebook.github.io/react/docs/reusable-components.html#es6-classes
class ReactComponent extends React.Component {
// https://facebook.github.io/react/docs/reusable-components.html#no-mixins
constructor(props) {
super(props);
this.state = {
baz: 'qux'
};
// https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
this._handleClick = this._handleClick.bind(this);
}
_handleClick() {
console.log(this);
this.setState({
baz: 'clicked'
});
}
render() {
return (
<div className={this.state.baz} onClick={this._handleClick}>
Lorem ipsum {this.props.foo} {this.props.bar}
</div>
);
}
}
ReactComponent.propTypes = {
foo: React.PropTypes.string
};
ReactComponent.defaultProps = {
bar: 42
};
export default ReactComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment