Skip to content
Advertisement

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?

Facebook:

var React = require("react");

var Component = React.createClass({
    render: function(){
        return (
            <div>{this.props.item}</div>
        );
    }
});

module.exports = Component;

AirBnB:

import React from "react";

export default class Component extends React.Component {
    render() {
        return (
            <div>{this.props.item}</div>
        );
    }
}

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

Advertisement

Answer

React components:

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

  • Function components using const MyComponent = () => {} or function MyComponent() + Hooks – The current standard of creating react components. The component is a function that returns the JSX to render. Hooks replace the life-cycle methods of the class components.

  • 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.

  • 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.

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement