ReactJS is a Javascript library for developing web components based on a virtual DOM. ReactJS has already become quite popular in the year that Facebook released it. In the near future, we can expect an interest in this library from more companies, because ReactJS allows you to create reliable, productive interfaces quickly.
A special feature of ReactJS is the use of a mixture of HTML and Javascript for greater readability, for example:
render: function () {
return <div>
<div class = "clicker" onMouseDown = {this.handleMouseDown}>
Give me the message!
</ div>
<div class = "message"> Message conveyed
<span class = "count"> {this.state.count} </ span> time (s) </ div>
</ div>
;
}
This language is called JSX and before using it in the browser, a special utility converts everything into simple Javascript. The result is:
')
render: function () {
return React.DOM.div (null,
React.DOM.div ({className: "clicker", onMouseDown: this.handleMouseDown},
"Give me the message!"),
React.DOM.div ({className: "message"}, "Message conveyed", React.DOM.span ({className: "count"}, this.state.count), "time (s)")
)
;
}
You can not use JSX and immediately write to Javascript, but this approach is more time consuming and less readable. On the other hand, using JSX imposes a number of requirements that are undesirable, such as:
* using an additional editor for JSX markup
* use of additional utility for precompiling JSX
* refusal to use TypeScript
Rejecting TypeScript is unacceptable for me, therefore such an idea was born: improve readability by applying a convenient object Javascript structure and then generate React.DOM code, again in Javascript, without JSX at all. It turned out like this:
render: function () {
var dom = [
{
tag: React.DOM.div,
props: {
className: "class1",
onClick: this.handleClick
},
content: "Hello" + this.state.value
},
{
tag: React.DOM.span,
props: {},
dom: [
{
tag: React.DOM.span,
props: {className: "class2"},
content: "Hello" + this.state.value
}
]
}
];
return parse (dom);
}
Thus, a structure is created based on an array of objects, each of which contains 3 properties: tag, props and dom (if there are nested objects) or content (if this object is leaf). The function that creates the code for ReactJS is:
function parse (dom, inner) {
var items = [];
for (var el in dom) {
if (dom [el] .dom) {
items.push (dom [el] .tag (dom [el] .props, parse (dom [el] .dom, inner || true)));
} else {
items.push (dom [el] .tag (dom [el] .props, dom [el] .content));
}
}
if (inner) {
return items.length == 1? items [0]: items;
} else {
return items.length == 1? items [0]: React.DOM.section (null, items);
}
}
According to the results, the approach was very convenient. There were no noticeable losses in drawing, but I do not rule out that on complex interfaces, you still have to create DOM based on React primitives. In any case, this optimization step can be performed at the final stage, after the completion of the actual components.