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?
2
Answers
1. Return the Array Directly (Recommended)
Pros:
Cons:
2. Use
React.createElement()
(If you need a wrapper)Pros:
div
), useful for layout control.Cons:
Conclusion:
createElement
if you need a container element.Either case can render the same output – that is without an additional wrapper of div tag.
The actual difference is in the amount of the code transpiled in each case.
The point is the latter case – React Component, will require an additional step of transipilation since it renders a React component. However this is entirely a technical aspect, a React developer should never be concerned about it.
The recommendation is React is a declarative language. It means a React developer describes the User Interface as opposed to tell the system how to make the UI as it is in an imperative way. Therefore please adhere to the design approach of the system and take the best productivity out of it. Avoid imperative codes like createElement. For more, request you may please go through the sections Thinking in React and https://react.dev/learn/describing-the-ui.
Please see below each case with codes, test results and transipled codes.
Case 1 : ordinary function
Output:
Case 2 : React component
Output
Please compare the code transpiled in each case. We can see below that there is an additional step in case of the React component.
Case 1 : ordinary function
Case 2 : React Component