I have a component that receives a raw text and some extended information. It enhances the text with this information and returns an array of text snippets and enhanced Components.
Initially, I created a function to do the transformation and return the transformed content, using React.createElement
:
const transform = (text, data) => {
// do the transformation
// ...
// In the end, I have this array consisting of text snippets and Components
transformedElements = [
'text',
<MyLink>Word</MyLink>,
'more text',
<MyLink>AnotherWord</MyLink>,
];
return React.createElement('div', null, transformedElements);
}
But then I wrote this as a Component:
const Transformed = ({text, data}) => {
// do the transformation ...
transformedElements = [
'text',
<MyLink>Word</MyLink>,
'more text',
<MyLink>AnotherWord</MyLink>,
];
return transformedElements;
// also works as:
// return React.createElement('div', null, transformedElements);
}
And I realized it would also work if I did return transformedElements
directly.
I'm guessing it performs better since it doesn't call createElement, and the only difference I could notice is that the returned components won't be wrapped in a containing element, like in the previous implementation.
So, should I call createElement
or just return the array? What are the pros, cons, and drawbacks of each approach, if any?
const Transformed = ({ text, data }) => {
const transformedElements = [
'text',
<MyLink key="word-link">Word</MyLink>,
'more text',
<MyLink key="another-word-link">AnotherWord</MyLink>,
];
return transformedElements; // Just return the array
};
React.createElement()
(If you need a wrapper)const transform = (text, data) => {
const transformedElements = [
'text',
<MyLink key="word-link">Word</MyLink>,
'more text',
<MyLink key="another-word-link">AnotherWord</MyLink>,
];
return React.createElement('div', null, transformedElements); // Creates a div wrapper
};
div
), useful for layout control.createElement
if you need a container element.