ffxsam
ffxsam

Reputation: 27713

Having trouble rendering a React element passed as a prop

I have the following component:

const Chip = (props) => {
  const ChipIcon = props.icon;
  let deleteButton = null;

  if (!props.readOnly) {
    deleteButton = <Delete
      style={styles.deleteButton}
      onTouchTap={props.onRemove}
    />
  }

  return <div className="Chip" style={styles.tag}>
    <ChipIcon />
    {' ' + props.label + ' '}
    {deleteButton}
  </div>
};

props.icon is definitely a Material UI SvgIcon, yet I get warnings when I try this.

arning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of Chip.

But this seems to work:

const Chip = (props) => {
  const chipIcon = props.icon;
  let deleteButton = null;

  if (!props.readOnly) {
    deleteButton = <Delete
      style={styles.deleteButton}
      onTouchTap={props.onRemove}
    />
  }

  return <div className="Chip" style={styles.tag}>
    {chipIcon}
    {' ' + props.label + ' '}
    {deleteButton}
  </div>
};

Why doesn't the first one work, if it's truly a React element?

Upvotes: 1

Views: 725

Answers (2)

VonD
VonD

Reputation: 5155

Your first example would work if ChipIcon was a React component. Your second example works, because chipIcon is a React element, i.e. already rendered component.

You can instantiate a component using jsx syntax this way: <MyComponent /> if MyComponent is a React component. If MyComponent is already a rendered component, you inject it using the syntax { MyComponent } as it already is a valid element. But is doesn't make much sense to use a rendered element as a component class : <MyComponent /> really is React.createElement(MyComponent, null).

Upvotes: 0

Buzinas
Buzinas

Reputation: 11725

Your icon property is already the element, and not the class that you use to render the element.

In JSX <ChipIcon /> would be transformed to React.createElement(ChipIcon, null). Your icon property is already the created element, not the class you pass to React to create the element for you.

Upvotes: 1

Related Questions