Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.createClass vs extends Component

Tags:

react-native

What's the different between

var MyClass = React.createClass({...}); 

To

class MyClass extends React.Component{...} 
like image 205
gran33 Avatar asked Nov 04 '15 16:11

gran33


People also ask

Is React createClass deprecated?

As of React 15.5, createClass is deprecated. You'll get warnings in the console if you're using it in your code – and, when React 16 comes out, createClass will be removed entirely.

What is createClass in React?

React. createClass allows you to generate component "classes." Under the hood, your component class is using a bespoke class system implemented by React. With ES6, React allows you to implement component classes that use ES6 JavaScript classes.

Why we use extends component in React?

Using the extends keyword, you can allow the current component to access all the component's properties, including the function, and trigger it from the child component. This example creates one component called ParentClass. jsx. ParentClass extends the component from React as React.

What is the React class which it needs to extend from?

For the React changes, we now create a class called “Contacts” and extend from React. Component instead of accessing React. createClass directly, which uses less React boilerplate and more JavaScript. This is an important change to note further changes this syntax swap brings.


2 Answers

These two ways depend on if you are using ES6 syntax or not, and they also change the way you set up your initial state.

When using ES6 classes, You should initialize state in the constructor.

When using React.createClass you have to use the getInitialState function.

ES6 Class Syntax:

class MyComponent extends React.Component {   constructor(props) {     super(props);     this.state = { /* initial state, this is ES6 syntax (classes) */ };   } } 

ES5 React.CreateClass syntax:

var MyComponent = React.createClass({   getInitialState() {     return { /* initial state */ };   }, }); 

These will both work the same way to set up initial state.

like image 70
Nader Dabit Avatar answered Oct 06 '22 12:10

Nader Dabit


With the class MyClass extends React.Component{...} syntax,

you can not use mixins and you need to bind the context of the method yourself

class MyClass extends Component {    constructor() {      super();      this.handleClick.bind(this);    }     handleClick() {      this.setState(...);    } } 

to me these are the biggest differences.

to replace the mixin, you can use a Container to wrap your component

export default Container(MyClass);  function Container(Component) {    var origin = Component.prototype.componentDidMount;    Component.prototype.componentDidMount = function() {       origin.apply(this, arguments);       /* do mixin */    } } 
like image 41
Sean Avatar answered Oct 06 '22 12:10

Sean