React Without ES6

React Without ES6

var createReactClass = require('create-react-class');
var Greeting = createReactClass({
  render: function() {
    return <h1>Hello, {this.props.name}</h1>;
  }
});

Normally you would define a React component as a plain JavaScript class. If you don’t use ES6 yet, you may use the create-react-class module instead.

Mixins in React without ES6

var SetIntervalMixin = {
  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.push(setInterval.apply(null, arguments));
  },
  componentWillUnmount: function() {
    this.intervals.forEach(clearInterval);
  }
};

var createReactClass = require('create-react-class');

var TickTock = createReactClass({
  mixins: [SetIntervalMixin], // Use the mixin
  getInitialState: function() {
    return {seconds: 0};
  },
  componentDidMount: function() {
    this.setInterval(this.tick, 1000); // Call a method on the mixin
  },
  tick: function() {
    this.setState({seconds: this.state.seconds + 1});
  },
  render: function() {
    return (
      <p>
        React has been running for {this.state.seconds} seconds.
      </p>
    );
  }
});

ReactDOM.render(
  <TickTock />,
  document.getElementById('example')
);

createReactClass lets you use a legacy mixins system for components that share some common functionality.

Declaring Default Props

//with ES6

class Greeting extends React.Component {
  // ...
}

Greeting.defaultProps = {
  name: 'Mary'
};


//without ES6

var Greeting = createReactClass({
  getDefaultProps: function() {
    return {
      name: 'Mary'
    };
  },

  // ...

});

With functions and ES6 classes defaultProps is defined as a property on the component itself. With createReactClass(), you need to define getDefaultProps() as a function on the passed object.

Setting the Initial State

//with ES6

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  // ...
}


//without ES6

var Counter = createReactClass({
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  // ...
});

In ES6 classes, you can define the initial state by assigning this.state in the constructor. With createReactClass(), you have to provide a separate getInitialState method that returns the initial state.

React Without ES6 — Structure map

Clickable & Draggable!

React Without ES6 — Related pages: