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"
/>
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.
Simpler approach is to have a fallback value be an empty string.
Works for type=number
as well.
<input type="number" value={estimatedHours || ''} />
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With