React elements
This book assumes that you are familiar with components and their instances, but there is another object you should know if you want to use React effectively: the Element.
Whenever you call createClass
, extend Component
, or simply declare a stateless function, you are creating a component. React manages all the instances of your components at runtime, and there can be more than one instance of the same component in memory at a given point in time.
As mentioned previously, React follows a declarative paradigm, and there's no need to tell it how to interact with the DOM; you just declare what you want to see on the screen and React does the job for you.
As you might have already experienced, most other UI libraries work in the opposite way: they leave the responsibility of keeping the interface updated to the developer, who has to manage the creation and destruction of the DOM elements manually.
To control the UI flow, React uses a particular type of object, called element, which describes what has to be shown on the screen. These immutable objects are much simpler compared to the components and their instances, and contain only the information that is strictly needed to represent the interface.
The following is an example of an element:
{ type: Title, props: { color: 'red', children: 'Hello, Title!' } }
Elements have a type, which is the most important attribute, and some properties. There is also a special property, called children, which is optional and represents the direct descendant of the element.
The type is important because it tells React how to deal with the element itself. In fact, if the type is a string, the element represents a DOM node, while if the type is a function, the element is a component.
DOM elements and components can be nested with each other, to represent the render tree:
{ type: Title, props: { color: 'red', children: { type: 'h1', props: { children: 'Hello, H1!' } } } }
When the type of the element is a function, React calls it, passing the props to get back the underlying elements. It keeps on performing the same operation recursively on the result until it gets a tree of DOM nodes, which React can render on the screen. This process is called reconciliation, and it is used by both React DOM and React Native to create the user interfaces of their respective platforms.