George
George

Reputation: 7317

What, formally speaking, is a react component?

Consider

var MyComponent = React.createClass({
  render: function() {
    //...
  }
});

as well as

var element = React.createElement(MyComponent);

Which specifically, or where specifically, is the "component"? Is it the object returned by the call to React.createClass(..)? Is it the object returned by React.createElement(..)? Is it behind the scenes somewhere in between?

Upvotes: 1

Views: 61

Answers (3)

George
George

Reputation: 7317

This post answers the question in great detail.

In short: components are -- literally speaking -- functions that take an object with a props field and, in turn, return a React.Element. Components can be pure functions, or JS classes (which are functions with syntactic sugar over them anyway). You can define a component via React.createClass; the output of React.createClass is -- as I understand it -- still literally a component (although several instances of it can be instantiated behind the scenes via React, each of which can be accesssed via this within the class definition; these instances are also components).

Finally, React.Element is nothing but a "description" of a component instance or a dom node. Literally, it is a javascript object with fields like props and children (it also has a field type, which is described in the article). Crucially, an instance of a React.Element is NOT a component; it merely describes one. Moreover, the output of a React.createClass() is a component, as well as any function that takes an object with a prop field and returns an instance of a React.Element.

Upvotes: 0

Carl Vitullo
Carl Vitullo

Reputation: 923

There's a post on the React blog that answers your question.

http://facebook.github.io/react/blog/2015/12/18/react-components-elements-and-instances.html

Basically, components are your class definitions, elements are created from your components in render(), and instances are your component's representation in the DOM.

Upvotes: 1

Obviously http://facebook.github.io/react/ is the authority here - a component is conceptual construct that has properties, state, and a render function. Although the first two are optional. Components are typed using a "class" (ES5 prototypes, ES6 classes, etc), which React is formally made aware of using the createClass function. Component instances are elements in a larger whole, loaded into a UI context (the browser, a phone, whatever), usually called an app, and created with createElement.

Upvotes: 0

Related Questions