Search code examples
reactjsmaterial-ui

Custom component in MUI textfield


I am trying to pass custom component to MUI TExtfield via InputProps->inputComponent.

But i am getting an error

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

I tried using createElement and few other options but i cant solve this ;-(

Only way this worked was passing a component and component props separately and then createElement but i would prefer the above solution if possible. Thank you

 componentProps={{
 dateFormat: 'dd MMMM yyyy',
 className: `form-control ${
 errors?.startedDate ? 'is-invalid' : ''
 }`,
 selected: field.value,
 popperClassName: 'popper_datepicker',
 }}
 component={DatePicker}

createElement(customComponent, {
 ...componentProps,
name,
onChange,
value,
})

thank you for any pointers

Code Sandbox

EDIT: edited code sandbox link


Solution

  • You need to modify your code so that you provide a function that returns a JSX element.

    Thus given the code in code sandbox, modify the below on how you provide DatePicker in customComponent prop:

          <CustomInput
            label="Starting Date"
            customComponent={() => <DatePicker dateFormat="dd MMMM yyyy" />}
          />
    

    Notice the () => <DatePicker dateFormat="dd MMMM yyyy" /> instead of <DatePicker dateFormat="dd MMMM yyyy" />