Search code examples
reactjsjsxreact-dom

Should I use React.createElement to return multiple children from a Component?


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?


Solution

  • 1. Return the Array Directly (Recommended)

    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
    };
    

    Pros:

    • Easier and cleaner to write.
    • Better performance (no extra wrapper).

    Cons:

    • No wrapper element, which may cause layout issues if a container is needed.

    2. Use 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
    };
    

    Pros:

    • Provides a parent wrapper (like a div), useful for layout control.

    Cons:

    • Adds an unnecessary wrapper if not required.
    • Slightly more verbose.

    Conclusion:

    • Return the array directly if you don’t need a parent wrapper.
    • Use createElement if you need a container element.