I use numeral to format my numbers from 4500000
to 4 500 000
.
The problem comes with cursor position - it gets wrong when the number of spaces is changing. I tried to save cursor position when my input is change, but something is wrong with it.
import React from "react";
import { render } from "react-dom";
import numeral from "numeral";
class App extends React.Component {
pricePosition = 0;
priceInput = React.createRef();
constructor(props) {
super(props);
numeral.localeData().delimiters.thousands = " ";
this.state = {
price: 4500000 // comes from props
};
}
componentDidUpdate() {
this.priceInput.current.selectionStart =
this.priceInput.current.selectionEnd = this.pricePosition; //tried like this
}
handleInputChange = field => ev => {
this[`${field}Position`] = Number(ev.target.selectionEnd);
this.setState({
[field]: Number(ev.target.value.replace(/\D/g, ""))
});
};
render() {
return (
<div>
Price here:
<input
ref={this.priceInput}
value={numeral(this.state.price).format("0,0")}
onChange={this.handleInputChange("price")}
/>
</div>
);
}
}
render(<App />, document.getElementById("root"));
Also you can check it: codesandbox