MeltingDog
MeltingDog

Reputation: 15490

How do I pass a component as a prop in React and Typescript?

I am new to React and am building a tab component using Material UI's Tabs component. I'd like to place the Material UI badge component within the Tab component's label prop, but I'm not sure how to go about this.

The Tab component looks as such:

        <Tab
          key={i}
          label={label}
          {...globalTabProps}
          {...tabProps}
          classes={{
            wrapper: cx('MuiTab-wrapper'),
          }}
        />

I'm trying to add the badge as such:

    const label = {
      <Badge
        color="primary"
        className={
          badgeProps.badgeContent === ''
            ? classNames(classes.MuiBadge, classes.MuiBadgeDotted)
            : classNames(classes.MuiBadge, classes.MuiBadgeNumber)
        }
        badgeContent={''}
        invisible={false}
        {...globalBadgeProps}
        {...badgeProps}
      ></Badge>
    };

Of course, this errors out (parsing error), but I don't think this is the correct way to handle this anyway.

Would anyone be able to point me in the right direction?

Many thanks!

Upvotes: 1

Views: 528

Answers (1)

glothos
glothos

Reputation: 38

You should wrap it with (), like so.

const label = (
      <Badge
        color="primary"
        className={
          badgeProps.badgeContent === ''
            ? classNames(classes.MuiBadge, classes.MuiBadgeDotted)
            : classNames(classes.MuiBadge, classes.MuiBadgeNumber)
        }
        badgeContent={''}
        invisible={false}
        {...globalBadgeProps}
        {...badgeProps}
      ></Badge>
    )

Note the () wrapping it.

Then do it like so:

       <Tab
          key={i}
          label={label}
          {...globalTabProps}
          {...tabProps}
          classes={{
            wrapper: cx('MuiTab-wrapper'),
          }}
        />

What it is done inside:

const WhateverComponent = (props) => (
  <div>
   ...
   {props.label}
  </div>
);

Upvotes: 2

Related Questions