1

My problem is I want to clear a masked text field from Office UI Fabric with a button. Has anybody a plan how to do this?

I tried to set the value with a state but that doesn't work.

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
Bernhard
  • 17
  • 5

1 Answers1

1

It appears MaskedTextField does nor support it directly, at least neither value property not setValue function not cause the component to re-render.

But the technique with remounting of components (see for example, here) comes to the rescue here. To reset a value, the new instance of MaskedTextField component is instantiated and mounted, for that matter the following component is introduced:

class MaskedTextFieldWrapper extends React.Component<any, any> {
  private textFieldRef: React.RefObject<MaskedTextField>;

  public generateKey(prefix:string): string {
    return `${ prefix }_${ new Date().getTime() }`;
  }

  public render(): JSX.Element {
    if(this.props.resetValue){
      return <MaskedTextField key={ this.generateKey("textfield")} value='' ref={this.textFieldRef} {...this.props} />;  
    }
    return <MaskedTextField ref={this.textFieldRef} {...this.props} />;
  }
}

Now the value of MaskedTextField could be reset like this:

class TextFieldExample extends React.Component<any, any> {

  constructor(props:any) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      resetValue: false
    };
}


  public handleClick():any {
    this.setState({resetValue: true});
  }

  public render(): JSX.Element {
    return (
      <div>
        <MaskedTextFieldWrapper resetValue={this.state.resetValue}  label="With number mask" mask='9999' />
        <PrimaryButton onClick={this.handleClick}>Clear</PrimaryButton>
      </div>
    );
  }

}

Demo

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193