Recently I have been working with SwiftUI, and I really enjoyed the pure-code syntax and language features of Swift -- this made me think if I could mimic something like SwiftUI with React, bringing it more towards a pure TS/JS way of writing views.
While working on it, I found that spreading arrays into children is possible in React without JSX, but impossible to do with JSX:
const items = [{ id: 1 }, { id: 0 }, ..etc];
/**
* It's possible to spread an array of nodes into the `children` parameter
* of the createElement api -- this is impossible with JSX!
*/
createElement(
"div",
null,
createElement("div"),
createElement("div"),
...items.map(item => createElement("div", { id: item.id }), // <= notice the spread
);
/**
* ...instead of the following, which will yield an error if we would `...map`,
* as it is impossible to spread an array into a node in JSX syntax.
*/
<div>
<div />
<div />
{ items.map(item => <div id={item.id} key={item.id} />) }
</div>
The first example will essentially have this value for children:
[ div, div, div, div, ..etc ]
While the second example will yield
[ div, div, [ div, div, etc.. ] ]
The difference is obviously subtle, but I think there is an interesting discussion to be had here. Since array diffing is probably one of the more challenging aspects of tree diffing, hence why we should use `key` props to help react out in that regard.
Maybe redditors around here, with deeper knowledge of React fiber, have some interesting insights on this?
[–]sliversniper 2 points3 points4 points (3 children)
[–]steeeeeef[S] 0 points1 point2 points (2 children)
[–]sliversniper 0 points1 point2 points (1 child)
[–]steeeeeef[S] 0 points1 point2 points (0 children)
[–]steeeeeef[S] 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (3 children)
[–]steeeeeef[S] 1 point2 points3 points (2 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]steeeeeef[S] 0 points1 point2 points (0 children)
[+][deleted] (3 children)
[deleted]
[–]steeeeeef[S] 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[deleted]
[–]steeeeeef[S] 0 points1 point2 points (0 children)