0

I was going through fabric UI TextField documentation(https://developer.microsoft.com/en-us/fluentui#/controls/web/textfield ) . I tried few examples of TextField with the following two handlers:-

  1. onChange
  2. onGetErrorMessage.

I tried few experiments with these two handlers (https://codepen.io/nishchay271095/pen/rNyPKYY?editors=1011 ):-

Case 1. When using both the handlers without any extra properties of TextField, both handlers(onChange and onGetErrorMessage) are called.

     <TextField
        label="Controlled TextField"
        onChange={onChangeSecondTextFieldValue}
        onGetErrorMessage = {onGetErrorMessageHandler}
      />

Case 2. When using both handlers with "defaultValue" property, both handlers(onChange and onGetErrorMessage) are called.

      <TextField
        label="Controlled TextField"
        defaultValue = "hello"
        onChange={onChangeSecondTextFieldValue}
        onGetErrorMessage = {onGetErrorMessageHandler}
      />

Case 3. When using both handlers with "value" property of TextField, only onChange() handler was called.

    <TextField
        label="Controlled TextField"
        value="hello"
        onChange={onChangeSecondTextFieldValue}
        onGetErrorMessage = {onGetErrorMessageHandler}
      />

Now, I'm having following doubts:-

  1. Why onGetErrorMessage() is not being called in case 3?
  2. How value and defaultValue properties affect the behavior of these two handlers(onChange and onGetErrorMessage)?

1 Answers1

1

Why onGetErrorMessage() is not being called in case 3?

When you have Uncontrolled Component there is no reason to use value property and onChange function, because TextField Component treats defaultValue as initial and it creates local state variable uncontrolledValue which interacts like when you have value prop.

So, in your case you have Uncontrolled Component and value property is excess.

Uncontrolled Component:

<TextField
  defaultValue="Hello"
  onGetErrorMessage={value => {
   if (value === 'Foo') {
     return 'Foo is not valid value';
   }
  }}
/>

Controlled Component

const [inputValue, setInputValue] = useState('Hello');

<TextField
  value={inputValue}
  onChange={(_, newValue) => {
    if(newValue || newValue === '') {
      setInputValue(newValue)
    }
  }}
  onGetErrorMessage={value => {
   if (value === 'Foo') {
     return 'Foo is not valid value';
   }
  }}
/>

How value and defaultValue properties affect the behavior of these two handlers(onChange and onGetErrorMessage)?

Answer lies in documentation:

defaultValue:

Default value of the text field. Only provide this if the text field is an uncontrolled component; otherwise, use the value property.

value:

Current value of the text field. Only provide this if the text field is a controlled component where you are maintaining its current state; otherwise, use the defaultValue property.

Full working example Codepen.

Marko Savic
  • 2,159
  • 2
  • 14
  • 27