cclloyd
cclloyd

Reputation: 9205

Material-UI TextField state incorrect after uncontrolled value change with react-hook-form

I have a Material-UI TextField element as below

<TextField
    variant='outlined' fullWidth
    name={'webhook'}
    label={'Webhook URL'}
    defaultValue={state.webhook}
    error={errors.webhook !== undefined}
    helperText={errors.webhook && 'Not a valid webhook URL.'}
    inputRef={register({
        required: true,
    })}
/>

And I control the value of the input using react-hook-form. It says as per the documentation that it is to be used with uncontrolled inputs as it controls the value of it through the useForm props.

So when I set the value from the default value of '' (empty string) to an actual value provided by a variable (non-empty string) using setValue from useForm(), the input label overlays the text in the center of the textfield instead of moving to the top as it would with an input that has a value.

Modifying the value of the field after the input's value gets set will make it work properly, but I need it to recognize that the value changed without modifying the value.

How can I get it to properly recognize that the value of the input has changed?

Example of image in glitched state:

Example of image in glitched state

Upvotes: 2

Views: 740

Answers (1)

Bill
Bill

Reputation: 19268

You want to take a look at Controller: https://react-hook-form.com/api#Controller

here is a codesandbox: https://codesandbox.io/s/react-hook-form-controller-079xx

<Controller name="test" control={control} as={TextField} />

Upvotes: 1

Related Questions