Jakub Koudela
Jakub Koudela

Reputation: 180

Forward ref with Material ui and custom component

i am having issue with forwarding ref using Material UI's Textfield with customComponent as InputProps

In short: I have a customized Mui Outlined Textfield. And it can either be input (just an ordinary text input) or have a custom component. In the example custom ToggleSwitch. And this is where all the issues start

Here is a link: Code SandBox

At the moment i am getting couple of errors:

and i am stuck. I have tried to wrap components with forwardRef but to no avail.

I am guessing iam using a wrong approach to this so any idea is welcome.

thank you

Upvotes: 0

Views: 369

Answers (1)

Chenxiang Wang
Chenxiang Wang

Reputation: 26

<CustomInput> is a Customized <TextField>.

In your case,

<TextField
  InputProps = {{
    inputComponent: customComponent,
  }}
/>

inputComponent: customComponent, should be:

  1. A native HTML element like input.
  2. A React component that is wrapped with React.forwardRef and can correctly handle refs.

BUT, inside of the "App.js", what you passed is a render function. Apparently, neither of the above two conditions is met.


    customComponent={(props) => {
      return (
        <CustomToggleSwitch {...props} offLabel="No" onLabel="Yes" />
      );
    }}

So, the thing is here: you need to pass a React component that is wrapped with React.forwardRef to customComponent.

Upvotes: 0

Related Questions