简体   繁体   中英

Objects are not valid react child when using React.createElement?

I have a simple text component:

import * as React from 'react'

interface IProps {
  level: 't1' | 't2' | 't3',
  size: 's' | 'm' | 'l' | 'xl' | 'xxl',
  subtle?: boolean,
  children: any,
}

const textSize = (size) => {
  if (size === 's') {
    return 'f6'
  }
  if (size === 'm') {
    return 'f5 fw3'
  }
  if (size === 'l') {
    return 'f4 fw5  lh-2'
  }
  if (size === 'xl') {
    return 'f3 fw5 lh-2 ls-025 ma0'
  }
  if (size === 'xxl') {
    return 'f2 fw5 lh-title ls-03125 ma0 mb3'
  }
}

const elements = {
  t1: 'h2',
  t2: 'h1',
  t3: 'span',
};


export const Text = ({ children, level, size, subtle, ...props }: IProps) => {
  return React.createElement(
    elements[level] || elements.t3,
    {className: textSize(size)},
    props,
    children,
  );
}

Which is used like so:

    <Text
      size='s'
      level={'t3'}>
        Hello world
    </Text>

However, when the line {className: textSize(size)}, is included in the main component I get the following error:

Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead. in span in Unknown`

Any ideas what can cause this?

Codesandbox

React.createElement takes 3 arguments, and you try to pass 4.

React.createElement(component, props, ...children)

In your case {className: textSize(size)} becomes props , and your props is actually children . You probably need to do something like

return React.createElement(
    elements[level] || elements.t3,
    {...props, className: textSize(size)},
    children,
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM