I’m trying to implement a text field that only allows numbers from 0 to 99. If the user enters a number that is negative or larger than 99, I want the textfield to reset to 0. Here is my code:
import * as React from "react";
import TextField from "@mui/material/TextField";
export default function TestForm() {
return (
<React.Fragment>
<TextField
required
id="field1"
name="field1"
label="How Many"
fullWidth
type="number"
defaultValue="0"
variant="standard"
onChange={function (event) {
if (event.target.value < 0 || event.target.value > 99) {
event.target.setValue("0");
}
}}
/>
</React.Fragment>
);
}
When I run this in CodeSandbox I get the following error:
event.target.setValue is not a function
Any advice would be appreciated.
>Solution :
I’m not familiar with a setValue property on an input element. But the react way to do it is to hold the value in local state using useState and make the TextField a controlled element by adding the value prop.
export default function TestForm() {
const [value, setValue] = React.useState(0)
return (
<TextField
value={value}
onChange={function (event) {
if (event.target.value < 0 || event.target.value > 99) {
setValue("0");
} else {
setValue(event.target.value)
}
}}
/>
);
}