Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing React number input control with blank value?

I'd like my controlled input to initialize with no value in the box. The input is a number, so I don't pass in an empty ''. Using defaultProps, I initialize the input with a null.

When typing into the input the console reports this message:

<MyInput> is changing an uncontrolled input of type number to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa).

To prevent this normally I initialize with an empty string to prevent this "switching" from happening. But with a number (I don't want to show a 0, I want nothing to show) I am not sure how to do it.

static defaultProps = {
    estimatedHours: null,
    estimatedMinutes: null,
  }

defalut values ^^

<input
   type="number"
   onChange={(e) => this.handleChange('Hours', e.target.value)}
   onKeyDown={this.handleKeyDown}
   onPaste={this.handlePaste}
   value={estimatedHours}
   placeholder={hoursText}
   className="slds-input th-trailmix-textbox th-time-component__input"
/>
like image 825
GN. Avatar asked Dec 04 '17 21:12

GN.


People also ask

How do you empty an input React?

To clear an input field with React, we can set the value of the value attribute to an empty string. We create the val state with the useState hook. Then we set the value prop of the input to the val state. Next we set the onClick prop of the button to a function that calls setVal to an empty string.


2 Answers

Simpler approach is to have a fallback value be an empty string. Works for type=number as well.

<input type="number" value={estimatedHours || ''} />
like image 163
GetSwifty Avatar answered Oct 11 '22 14:10

GetSwifty


You can set value Undefined,

Also add a check for input type if required

class Input extends React.Component {

    constructor(props) {
        super(props);
        this.state = {value: undefined};

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange = (event) => {
        const isnum = /^\d+$/.test(event.target.value);
        if (isnum) {
            return this.setState({
                value: Number(event.target.value),
            });
        }
    };

    render() {
        return (
            <input
                type="number"
                onChange={this.handleChange}
                value={String(this.state.value)}
                placeholder={"Please enter number"}
            />
        );
    }
}

and convert String to Number and vice versa

This won't throw you an error for uncontrolled input

like image 30
Nishant Avatar answered Oct 11 '22 15:10

Nishant