Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React – trying to validate textfield input – "event.target.setValue is not a function"

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
                }
            }}
        />
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading