How to prevent nullable input in React Numeric TextBox

03 Sep 20264 minutes to read

By default, the React 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 React Numeric TextBox 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'));