When working with forms in ReactJS, you may encounter scenarios where you need to accept floating-point numbers as input from users. In this article, we will explore how to set an input box to accept floating numbers in ReactJS and handle the validation of the entered values.
If we want to set the input box to be a floating number then we can use the step attribute of the input tag. We have to set the input type as the number and step value by which we want to increase/decrease the floating number. We can also set min and max attributes such that the number will not decrease after the min value and will not increase after the max value.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example:
App.js
Javascript
import React from 'react' class App extends React.Component { state = { value: 10 } onValueChange = (event) => { this .setState({ value: event.target.value }) } render() { return ( <td> <label> Floating Number: </label> <input type= 'number' step= "0.1" min= '0' max= '20' value={ this .state.value} onChange={(event) => this .onValueChange(event)} /> </td> ) } } export default App; |
Output: