How to set min or max attributes on TextField with type number?

Sometimes, we want to set min or max attributes on TextField with type number.

In this article, we’ll look at how to set min or max attributes on TextField with type number.

How to set min or max attributes on TextField with type number?

To set min or max attributes on TextField with type number, we set the InputProps prop to an object that has the inputProps property which has the min and max properties.

For instance, we write:

import { TextField } from "material-ui";
import React, { useState } from "react";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";

const min = -10;
const max = 10;

export default function App() {
  const [value, setValue] = useState(0);

  return (
    <MuiThemeProvider>
      <div>
        <TextField
          type="number"
          inputProps={{ min, max }}
          value={value}
          onChange={(e) => {
            if (e.target.value === "") {
              setValue(e.target.value);
              return;
            }
            const value = +e.target.value;
            if (value > max) {
              setValue(max);
            } else if (value < min) {
              setValue(min);
            } else {
              setValue(value);
            }
          }}
        />
      </div>
    </MuiThemeProvider>
  );
}

We set the onChange prop to a function that checks the input value, which is stored in e.target.value.

If e.target.value is an empty string, we call setValue to store the value so we can clear the input.

Otherwise, we convert e.target.value to a number with the + operator and assign the number to value.

If value is bigger than max, we call setValue with max to set value to max.

Similarly, we set value to min if value is less than min.

Otherwise, we call setValue with value to set the value state to value.

Also, we set the value prop to the value state so that we see the input value displayed in the text field.

Conclusion

To set min or max attributes on TextField with type number, we set the InputProps prop to an object that has the inputProps property which has the min and max properties.