score:2

Accepted answer

your textfield is currently uncontrolled because it doesn't have a value property. that means when you change number, it has no effect on the textfield, because the textfield's content isn't controlled by your code. to make it controlled, add value={number} to it. then, clearinfo works correctly:

const { usestate } = react;
const { textfield } = materialui;

const example = () => {
    const [number, setnumber] = usestate("");

    const handlenumber = (evt) => {
        const num = evt.target.validity.valid ? evt.target.value : number;
        setnumber(num);
    };

    const clearinfo = () => {
        //other fields here
        // setfirstname("");
        // setlastname("");
        setnumber("");
    };

    const handlesubmit = (e) => {
        e.preventdefault();
        try {
            //codes here
            // updatedata();
            clearinfo();  
        } catch (err) {
            console.log(err);
        }
        // setopen(true); //for the alert
    };

    return <form onsubmit={handlesubmit}>
        <textfield
            type="number"
            pattern="[0-9]*"
            variant="outlined"
            label="phone number"
            fullwidth
            onchange={handlenumber}
            value={number}
            required
            inputprops={{
                maxlength: 11,
            }}
            inputprops={{
                disableunderline: "true", // *** changed case and value per error from react
            }}
        />
        <button>submit</button>
    </form>;
};

reactdom.render(<example />, document.getelementbyid("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@mui/material@5.5.0/umd/material-ui.development.js"></script>

i had to make two other changes there (other than commenting out missing functions, etc.) for the snippet to work without errors:

  1. i removed the async from handlenumber because it didn't have any await in it and unfortunately stack snippets using jsx don't support async/await (because they use a really old version of babel; please vote to fix that here).

  2. react logged a warning about disableunderline: true in inputprops saying (in effect) to make it disableunderline: "true" instead, so i did that.


Related Query

More Query from same tag