Conditionally use material-ui default prop

I have a StepLabel component in material ui. Depending on the props passed to the parent, I may want to change the icon prop of the StepLabel:

interface Props {
  customClasses?: ClassNameMap;
  customIcon?: ReactNode;
}

const MyStepComponent = (props: Props) => {

  const { customClasses, customIcon } = props

  return (
    <Stepper {...stepperProps}>
      <Step
        icon={
          customIcon
            ? React.cloneElement(customIcon as React.ReactElement, {
                className: customClasses?.stepIcon
              })
            : null
          }
        {...otherStepProps}
      />
    </Stepper>
  )

}

So in this scenario, if a customIcon is passed to MyStepComponent it will render that icon instead of the default, and if customClasses is passed as well, it will apply some of those custom classes to that icon. Great.

But in the event that customIcon is not passed, I would like for the Step component to just use its default icon (which is the blue circle with the step number in it). However, in my code, it does not render the default icon, it renders null.

How can I tell the Step to use my customIcon if it exists, but if not, use the default?

1 answer

  • answered 2021-03-08 17:42 Razvan Bunga

    if the customIcon is truthy then the first if will be triggered and the component with the custom icon will be rendered.

     const MyStepComponent = (props: Props) => {
    
          const { customClasses, customIcon } = props
          
          if (customIcon) {
            return (
                <Stepper {...stepperProps}>
              <Step
                icon={ React.cloneElement(customIcon as React.ReactElement, {
                        className: customClasses?.stepIcon
                      })
                  }
                {...otherStepProps}
              />
            </Stepper>
            )
          }
    
          return (
            <Stepper {...stepperProps}>
              <Step
                icon={defaultIcon}
                {...otherStepProps}
              />
            </Stepper>
          )
    
        }