marco
marco

Reputation: 1140

Creating a component in React.js: is "React.createClass" still usable?

Some months ago I began to study react.js, then I abandoned it. Today I have begun to study React again. Reading the official documentation I find that the syntax of how to create a component has changed. In the past I learned to create a component in this way:

reactComponentElement = React.createClass({
   render: function(){
      return <h1>Title</h1>;
   }
})

so, using React.createClass.

Today I see in the docs that the creation of a component can be achieved with a function

function reactComponentElement(){
   return <h1>Title</h1>;
}

or with a class

class Clock extends React.Component {
   render() {
      return (
         <div>
            <h1>Hello, world!</h1>
         </div>
      );
   }
}

So, can I still use React.createClass?

Upvotes: 0

Views: 153

Answers (3)

Alessandro Scandone
Alessandro Scandone

Reputation: 157

I strongly suggest you to only use function components (a function from props to html) + hooks.

They are simple to reason with, future proof, and hooks make code super simple and less verbose to reuse

Upvotes: 0

Falk
Falk

Reputation: 637

If I am coding in ES 5.1 I am still using the syntax:

var ComponentName = React.createClass({
    render: function() {
        return (
            <some JSX />
        )
    }
})

However, when I am writing ES 6 syntax, I use the extends declaration if I want a 'smart' or class based component (one that displays and messes with data):

import React, { Component } from 'react'

class ComponentName extends Component {
    render() {
        return (
            <some JSX />
        )
    }
}

But not every component needs that and I can just as well declare functional components (I call these 'dumb' components because I simply use those to get something on the screen) in ES 6:

const ComponentName = () => {
    return (
        <some JSX />
    )
}

I noticed in the React documentation that there is a mismatch between ES5 and ES 6 syntax (as in some pages are still in ES 5, others are in ES 6). You can find the ES6 syntax here: https://facebook.github.io/react/docs/react-component.html

Upvotes: 3

Piotr Sołtysiak
Piotr Sołtysiak

Reputation: 1006

In function

function reactComponentElement(){
   return <h1>Title</h1>;
}

you are not creating react component wit all it's meaning - you just return some JSX. Classes are available only in ES6 and higher, so if you code in ES5, you still have to use React.createClass(); React.Component

Upvotes: 0

Related Questions