How to prevent nullable input in React NumericTextBox

9 Aug 20264 minutes to read

By default, the NumericTextBox value can be set to null when the input is cleared. For applications requiring a value to always be present, use the following sample to enforce a non-null value and prevent users from creating empty NumericTextBox inputs.

import { NumericTextBoxComponent } from '@syncfusion/ej2-react-inputs';
import * as React from "react";
import * as ReactDOM from "react-dom";
export default class App extends React.Component {
    numericInstance;
    numericValue = 0;
    constructor(props) {
        super(props);
        this.onCreate = this.onCreate.bind(this);
        this.onBlur = this.onBlur.bind(this);
    }
    // prevents nullable value during initialization
    onCreate() {
        if (this.numericInstance.value == null) {
            this.numericInstance.value = 0;
            this.numericInstance.dataBind();
        }
    }
    onBlur(args) {
        if (args.value == null) {
            this.numericInstance.value = 0;
            this.numericInstance.dataBind();
        }
    }
    render() {
        return (<NumericTextBoxComponent id="numeric" value={this.numericValue} ref={(numeric) => { this.numericInstance = numeric; }} created={this.onCreate} blur={this.onBlur}/>);
    }
}
ReactDOM.render(<App />, document.getElementById('numeric1'));
import { NumericBlurEventArgs, NumericTextBoxComponent } from '@syncfusion/ej2-react-inputs';
import * as React from "react";
import * as ReactDOM from "react-dom";

export default class App extends React.Component<{}, {}> {
  public numericInstance: any;
  public numericValue: number = 0;
  constructor(props: any) {
    super(props);
    this.onCreate = this.onCreate.bind(this);
    this.onBlur = this.onBlur.bind(this);
  }

  // prevents nullable value during initialization
  public onCreate() {
        if (this.numericInstance.value == null) {
              this.numericInstance.value = 0;
              this.numericInstance.dataBind()
        }
  }
  public onBlur(args: NumericBlurEventArgs) {
        if (args.value == null) {
            this.numericInstance.value = 0;
            this.numericInstance.dataBind()
        }
    }
  public render() {
    return (
      <NumericTextBoxComponent id="numeric" value={this.numericValue} ref={(numeric) => { this.numericInstance = numeric as NumericTextBoxComponent; }} created={this.onCreate} blur={this.onBlur} />
    );
  }
}
ReactDOM.render(<App />, document.getElementById('numeric1'));