ItSolutionStuff.com

React - How to Allow Only Numbers in Textbox?

By Hardik Savani • September 5, 2020
React JS

Today, i will let you know example of allow only numbers in textbox react js. This article will give you simple example of allow only numbers in input field react. i explained simply about only numbers allowed in textbox reactjs. This tutorial will give you simple example of react allow only numbers in input.

In this example, i will show you simple example of allow only number in input text field in react js. we will write that code on change event. i take one number text field and you can only enter number in that textbox.

So, let see bellow example code for enter only number in textbox react js.

Example Code:

import React, { Component } from 'react';

import { render } from 'react-dom';

class App extends Component {

constructor() {

super();

this.state = {

number: ''

};

this.handleChange = this.handleChange.bind(this);

this.handleSubmit = this.handleSubmit.bind(this);

}

handleChange(event) {

const re = /^[0-9\b]+$/;

if (event.target.value === '' || re.test(event.target.value)) {

this.setState({number: event.target.value})

}

}

handleSubmit(event) {

console.log(this.state);

event.preventDefault();

}

render() {

return (

<div>

<h1>How to Allow Only Numbers in Textbox in React - ItSolutionStuff.com</h1>

<form onSubmit={this.handleSubmit}>

<input

type="text"

value={this.state.number}

onChange={this.handleChange} />

<input type="submit" value="Submit" />

</form>

</div>

);

}

}

render(, document.getElementById('root'));

Now we are ready to run our application, so let's run using bellow command:

npm start

Open bellow url:

http://localhost:3000

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

React Email Validation Example

Read Now →

React Form Validation Tutorial Example

Read Now →

React Multi Select Dropdown Example

Read Now →

React Multiple Checkboxes Example

Read Now →

React Checkbox onchange | React Checkbox Example

Read Now →

React Radio Button onchange | React Radio Button Example

Read Now →

React Select Dropdown onchange | React Select Box Example

Read Now →

How to Change Date Format in React?

Read Now →

React If Else If Condition in Render Example

Read Now →

React Bootstrap Modal Popup Example

Read Now →