Want to allow only numbers in textbox in reactjs? Use controlled component (use value and onChange property of input field), and inside onChange handle check whether the entered value is proper number or not. Update the state only when entered value is a valid number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class App extends React.Component{ constructor(){ super(); this.state = {value: ''}; this.onChange = this.onChange.bind(this) } onChange(e){ const re = /^[0-9\b]+$/; if (e.target.value === '' || re.test(e.target.value)) { this.setState({value: e.target.value}) } } render(){ return <input value={this.state.value} onChange={this.onChange}/> } } ReactDOM.render(<App/>,document.getElementById('app')) |
1 2 3 4 | <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='app'/> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.