Simpler approach is to have a fallback value be an empty string.
Works for type=number as well.
<input type="number" value={estimatedHours || ''} />
Answer from GetSwifty on Stack OverflowSimpler 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
reactjs - How to make an input of type number a controlled component in react - Stack Overflow
Only numbers. Input number in React - javascript
reactjs - React controlled <type='number'> input allows typing in letter? - Stack Overflow
Only numbers. Input number in React
» npm install @react-input/number-format
Simply way in React
<input
onKeyPress={(event) => {
if (!/[0-9]/.test(event.key)) {
event.preventDefault();
}
}}
/>
I tried to mimic your code and noticed that there's an issue on React with <input type='number' />. For workaround, check this example and try it yourself: https://codepen.io/zvona/pen/WjpKJX?editors=0010
You need to define it as normal input (type='text') with pattern for numbers only:
<input type="text" pattern="[0-9]*"
onInput={this.handleChange.bind(this)} value={this.state.financialGoal} />
And then to compare the validity of input:
const financialGoal = (evt.target.validity.valid) ?
evt.target.value : this.state.financialGoal;
The biggest caveat on this approach is when it comes to mobile --> where keyboard isn't in numeric but in normal alphabetic format.
You can use this code:
<input id = 'prepFormInput' type='number' className='prepNumber' value={props.prepField.numeral} onChange={props.handlePrep} placeholder='prep time' onkeydown="javascript: return ['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code) ? true : !isNaN(Number(event.key)) && event.code!=='Space'" />
This will avoids all characters that are not numbers!
This part make's input accept only numbers:
!isNaN(Number(event.key))
This part make's accept the arrow and delete keys:
['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code)
This part make's Firefox disallow spaces in numbers:
event.code!=='Space'
(For react Applications)
If someone has text input and wants to accept only whole numbers. You can use the following code.
const numberInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
const eventCode = event.code.toLowerCase();
if (!(event.code !== null
&& (eventCode.includes("digit")
|| eventCode.includes("arrow")
|| eventCode.includes("home")
|| eventCode.includes("end")
|| eventCode.includes("backspace")
|| (eventCode.includes("numpad") && eventCode.length === 7)))
) {
event.preventDefault();
}
};
I have compared the length of eventCode to 7 when it includes numpad because its actual value is like numpad0, numpad1 ... numpad9
This function can be specified in onKeyDown such as
<input
id="myNumberInput"
type="text"
placeholder="numeric input"
onKeyDown={numberInputKeyDown}
/>
To extent field to accept decimals or negative numbers you can console.log the eventCode in numberInputKeyDown to check your required key code and add it in if statement.
Simply way in React
<input
onKeyPress={(event) => {
if (!/[0-9]/.test(event.key)) {
event.preventDefault();
}
}}
/>
I tried to mimic your code and noticed that there's an issue on React with <input type='number' />. For workaround, check this example and try it yourself: https://codepen.io/zvona/pen/WjpKJX?editors=0010
You need to define it as normal input (type='text') with pattern for numbers only:
<input type="text" pattern="[0-9]*"
onInput={this.handleChange.bind(this)} value={this.state.financialGoal} />
And then to compare the validity of input:
const financialGoal = (evt.target.validity.valid) ?
evt.target.value : this.state.financialGoal;
The biggest caveat on this approach is when it comes to mobile --> where keyboard isn't in numeric but in normal alphabetic format.
» npm install react-numeric-input
» npm install rc-input-number
Hi, I am using shadcn with react hook form. My form has two input fields. One is string and other is number. Here's my code.
If I am not using value and onChange inside Input then it gives me this error.A component is changing an uncontrolled input to be controlled
If I am setting value as empty string then I am not able to clear the input after entering the value. Value is 0 when I try to clear the field.
Any way to resolve this??