Reputation: 659
Consider this simple react component that has an input field, which I'd like to constrain to have a minimum value of 20:
class InputTest extends React.Component {
constructor(props) {
super(props);
this.state = {
val: 20,
};
}
valChange = event => {
let newVal = event.target.value;
if (newVal >= 20) {
this.setState({
val: newVal,
});
}
};
render() {
return (
<div>
<input
type={'number'}
value={this.state.val}
onChange={this.valChange}
/>
</div>
);
}
}
Now everything more or less works fine with this, unless I try to type in a brand new number into the field.
e.g. if I want to select the number currently in the field and overwrite it with lets say 243.
As I highlight the number and press the "2" key, the react component rejects number 2 as it is smaller then 20, and I am unable to comfortably type the number in.
I am wondering if there already exists some kind of a solution to this.
If not I could probably build something with some kind of a delayed constraint check.
EDIT: I should have mentioned this, but I only decided to add the most simple example to make things clearer. In my case I also had a slider bound to the input field, so I'd want change the slider position as the value inside input changes and vice versa. So simply notifying the user won't work, as the slider's min and max values are what's constraining the input.
I ended up using a debounce function to delay the slider position change.
Upvotes: 1
Views: 1157
Reputation: 1456
Wrap your input
inside a form
and add the min
and (max
if you want) attributes. Press Enter
or Submit
to see the notification (You can remove the button if you don't want it)
<form>
<input type = "number" min = 20 />
<input type = "submit" value = "submit" />
</form>
And remove the condition in your valChange
function you don't need it anymore.
Upvotes: 1