Ivan Ivan - 1 year ago 110
React JSX Question

React Components - What is the proper way to create them?

I'm learning React and I came across two different ways to create components. One is by Facebook and the other by AirBnB. I also saw them in the tutorials I've been watching.

This may be a stupid question, but which one is better?


var React = require("react");

var Component = React.createClass({
render: function(){
return (

module.exports = Component;


import React from "react";

export default class Component extends React.Component {
render() {
return (

Disclaimer: I may have errors in the code, so please forgive me and just focus on the style.

Answer Source

React components:

You have 4 basic ways of creating a reusable React component:

  • React.createClass({}) - the old way, doesn't require transpiling, but since you'll probably use JSX, you'll need transpiling anyway. Still appears in old React tutorials, but will be deprecated eventually.

  • class MyComponent extends React.Component {} - the ES6 way of creating a stateful component. Requires transpiling via babel, which also handles JSX. If you need state, and lifecycle methods - use this.

  • class MyComponent extends React.PureComponent {} - new in React 15.3.0. Same as React.Component, but with a PureRenderMixin like functionality, since ES6 components don't support mixins.

  • const MyComponent = () => {} or function MyComponent() - stateless component without lifecycle methods. Requires transpiling if you create it using arrow function. Use it for simple display components.

JS modules:

Nodejs syntax (commonjs) uses require() and ES6 uses import. You can use whatever you like, and even mix the two, but the ES6 modules way of import/exporting is a bit more 'standard' for react components. For now import is actually transpiled by babel to require anyway. Both require and import need some sort of a bundling tool, such as webpack or browserify to work in a browser.

render() vs .render:

The render() is the ES6 way of defining a method in ES6 classes.

React.createClass({}) requires a JS object literal. In ES5, defining methods in object literals uses the prop: function() {} syntax, such as render: function() syntax. btw - In ES6 you can actually write the method in the literal as render() instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download