0

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

1
  • why do you have curly brackes {} wrapping this line? Commented Nov 15, 2020 at 9:45

1 Answer 1

1

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,
  );
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks for the answer, unfortunately the error still persists. I've updated the question with a Codesandbox

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.