Home > Back-end >  How to create forms with MUI (material ui)
How to create forms with MUI (material ui)

Time:07-24

Hiho,

I want to use mui in my current react project. Is there a different/better way to create forms than the following example?:

    const [companyName, setCompanyName] = useState<string>("");
    const [companyNameError, setCompanyNameError] = useState<boolean>(false);
    const changeName = (event: React.ChangeEvent<HTMLInputElement>) => {
        if(event.target.value === "") {
            setCompanyNameError(true);
        } else {
            setCompanyNameError(false);
        }

        event.preventDefault();
        setCompanyName(event.target.value);
    }

    const anyInputFieldEmpty = () => {
        var result = false;
   
        if(companyName === "") {
            setCompanyNameError(true);
            result = true;
        } else {
            setCompanyNameError(false);
        }
        
        // add the same check for all other fields. My real code has multiple input fields

        return result;
    }

    const resetFields = () => {
        setCompanyName("");
    }

    return (
        <div>
            <TextField
                required
                fullWidth
                label="Company Name"
                margin="dense"
                name="companyName"
                value={companyName}
                onChange={changeName}
                helperText={companyNameError ? "Company name is not allowed to be empty!" : ""}
                error={companyNameError}
            />

            <Button
                sx={{ alignSelf: 'center', }}
                variant="contained"
                onClick={() => {
                    if(!anyInputFieldEmpty()) {
                        onSubmitClick(); // some function from somewhere else, which triggers logic
                        resetFields(); // This form is in a popover. The values should be resetted before the user open it again.
                    }
                }}
            >
                Create
            </Button>
        </div>);

It feels wrong to do the validation this way if I use multiple textfields (up to 9). Its a lot of boilerplate code and if I add further validation rules (for example a minimum character count) it goes crazy.

Is this the right way to achive my goal?

T

CodePudding user response:

MUI does not have a native form validator i recommend using react-hook-form yup it's pretty simple and has a lot of tutorials

screenshot

An example project could be found on this codesandbox

CodePudding user response:

As others have mentioned. Formik and Yup works great for validation. Formik also provides a way to easily disable your submit buttons. Here is a codesandbox : https://codesandbox.io/s/long-butterfly-seogsw?file=/src/App.js

  • Related