How to accept only positive unsigned integer values in TextField with React Material-UI?

Sometimes, we want to accept only positive unsigned integer values in TextField with React Material-UI.

In this article, we’ll look at how to accept only positive unsigned integer values in TextField with React Material-UI.

How to accept only positive unsigned integer values in TextField with React Material-UI?

To accept only positive unsigned integer values in TextField with React Material-UI, we can check the value that’s entered into the TextField, then we can change values that aren’t accepted to a valid value.

For instance, we write:

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

const min = 1;

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

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

We set the onChange prop to a function that checks the inputted value.

The inputted value is stored in e.target.value.

If it’s less than min, then we set the value state to min with setValue.

Otherwise, we set value to e.target.value.

And we set the value prop to the value state.

Conclusion

To accept only positive unsigned integer values in TextField with React Material-UI, we can check the value that’s entered into the TextField, then we can change values that aren’t accepted to a valid value.