Search code examples
reactjstypescripterror-handlingcomponentsjsx

nesting components with createElement in React yields error


I'm trying to create a helper function that nest a passed element/component as a children of itself of several depths.

So something like this

const Chain = nested(4, () => <div />)
return (
  <Chain />
)

Should render divs nested 4 levels

<div>
  <div>
    <div>
      <div />
    </div>
  </div>
</div>

I implemented the function in React like this.

/** nest the given element in itself of specified depth */
export const nested = (
  depth: number,
  element: () => JSX.Element
): FC<any> => () => {

  let chain = element();
  for (let i = 0; i < depth; i++) {
    chain = React.createElement(
      element().type,
      element().props,
      chain
    );
  }
  return chain;
};

It renders and displays the nested Divs correctly, but gives back an error message i don't understand how to correct.

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

Solution

  • Try going with a recursive solution.

    const createInnerElements = (count, childElement) => {
       if (count == 1) {
         return <div>{childElement}</div>
       }
       return createInnerElements(count - 1, <div>{childElement}</div>);
    }
    
    // in your parent component,
    return <>{createInnerElements(4, <></>)}</>