3 ms·
> People get confused because they don't remember that JSX is just a tree of nested React.createElement function calls, so they decide that they should mix loop
by root_axis 9y ago
> People get confused because they don't remember that JSX is just a tree of nested React.createElement function calls, so they decide that they should mix looping logic into a block of JSX because that's what they'd do in PHP even though you'd obviously not do that when looking at raw code.
Basically what I'm saying is, if you were just writing React.createElement function calls, it'd be more obvious that the items.map should kept out of the rendering code, e.g.
const MyComponent = function MyComponent(props) {
return React.createElement(
"div",
null,
React.createElement(
"h1",
null,
"List of items"
),
React.createElement("br", null),
props.itemData.map(function (itemData) {
return React.createElement(Item, { data: itemData });
});
);
};
Of course, this is a simplified example, but the more complex the template (i.e. the deeper the nesting) the more the code benefits from having loops and other control structures extracted from the final template.
- dwaltrip 9y agoWhen a programming expression is made significantly more concise via some abstraction, it can be used in new ways that weren't reasonable before. JSX makes expressing dynamic, declarative DOM markup concise enough that a short expression such as: `items.map(item => <FooItem item={item}/>` is no longer overly obtuse/obfuscating. If the `map` expression becomes much larger, it might make sense to refactor it out in some way. But I would argue that the important guiding principle here is readability and modularity. Drawing a hard line between flow/control structures and "template code" is not useful, in my mind. As others have stated in this thread, the more useful distinction is between business logic and presentation. Loops rightfully exist in both of those domains.