showing results for - "formatting input type number in react"
Deborah
05 Feb 2017
1import React from "react";
2import PropTypes from "prop-types";
3
4class NumberField extends React.Component {
5  constructor(props) {
6    super(props);
7    this.state = { isEditing: false };
8  }
9
10  onChange(event) {
11    this.props.onChange(event.target.value);
12  }
13
14  toCurrency(number) {
15    const formatter = new Intl.NumberFormat("sv-SE", {
16      style: "decimal",
17      currency: "SEK"
18    });
19
20    return formatter.format(number);
21  }
22
23  toggleEditing() {
24    this.setState({ isEditing: !this.state.isEditing });
25  }
26
27  render() {
28    return (
29      <div>
30        <label htmlFor={this.props.name}>Income</label>
31        {this.state.isEditing ? (
32          <input
33            type="number"
34            name={this.props.name}
35            value={this.props.value}
36            onChange={this.onChange.bind(this)}
37            onBlur={this.toggleEditing.bind(this)}
38          />
39        ) : (
40          <input
41            type="text"
42            name={this.props.name}
43            value={this.toCurrency(this.props.value)}
44            onFocus={this.toggleEditing.bind(this)}
45            readOnly
46          />
47        )}
48      </div>
49    );
50  }
51}
52
53NumberField.propTypes = {
54  name: PropTypes.string,
55  value: PropTypes.string,
56  onChange: PropTypes.func
57};
58
59export default NumberField;
60