Chapter 2. The Life of a 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:
varMyComponent=React.createClass({/* specs */});
The “specs” is a JavaScript object that has one required method called render() and a number of optional methods and properties. A bare-bones example could look something like this:
varComponent=React.createClass({render:function(){returnReact.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, and that’s why you see the span in the snippet; you cannot just return text.
Using your component in an application is similar to using the DOM components:
ReactDOM.render(React.createElement(Component),document.getElementById("app"));
The result of rendering your custom component is shown in Figure 2-1.
Figure 2-1. Your first custom component
React.createElement() is one way to create an “instance” of your component. Another way, if you’ll be creating several instances, is to use a factory:
varComponentFactory=React.createFactory(Component);ReactDOM.render(ComponentFactory(),document.getElementById("app"));
Note that the React.DOM.* methods you already know of are actually just convenience wrappers around ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access