I have the following react component:
var App = React.createClass({
getInitialState: function() {
return {value: 4.5}
},
change: function(event) {
this.setState({value: parseFloat(event.target.value)});
},
render: function() {
return <input type="number" value={this.state.value} onChange={this.change}/>;
}
});
React.render(<App/>, document.body);
You can see it here: http://jsfiddle.net/2hauj2qg/
The problem is that if I want to type in a number like: "4.7". When the user enters, "4.", it becomes "4", due to being converted to a float in back. But this interrupts what the user was typing. What's the recommended way of solving this problem?
Remove the parseFloat and your string won't be cast to a number?
http://jsfiddle.net/2hauj2qg/1/
If it doesn't make sense to do anything with the number until they're done typing and you follow the standard way of raising an event to signal changed data, you can accomplish it with the following:
It doesn't make too much sense in this isolated example, but if you assume someone is using MyComponent and that they give it an onChange callback, then this works nicely. You get the benefits of a native input control but still return (through the callback) the number as an actual float.
As imjared mentioned, it's because you're using parseFloat
Instead, you may wish to only allow digits and the decimal. It stays stored as a string and never changes their input, but they're prevented from typing things like letters and spaces.
To allow negative numbers you need to do this:
To enforce a leading dollar sign and no more than two decimals, and if the first character (after the $) is the decimal, prefix it with 0.
What about writing a small component that will handle string values and pass only legal float values to the listeners ?