Tutorial – React.js Life component

Now that you know how to use the ready-made DOM components, it’s time to learn how to make some of your own.

Bare minimum

The API to create a new component looks like this:

var MyComponent = React.createClass({
  /* specs */
});

The “specs” is a JavaScript object that has one required method render() and a number of optional methods and properties. A bare-bone example could look something like this:

var Component = React.createClass({
  render: function() {
    return React.DOM.span(null, "I'm so custom");
  }
});

As you can see, the only thing you must do is implement the render() method. This method must return a React component, that’s why you see the span in the snippet above.

Using your component in an application is similar to using the DOM components:

React.render(
  React.createElement(Component),
  document.getElementById("app")
);

Figure 2-1. Your first custom component

The React.createElement() is one way to create an “instance” of your component. Another way, if you’ll be creating several instances, is to create a factory:

var ComponentFactory = React.createFactory(Component);

React.render(
  ComponentFactory(),
  document.getElementById("app")
);

Note that the React.DOM.* methods you already know of are actually just convenience wrappers aroundReact.createElement(). In other words, this code also ..

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares