Code92
Code92

Reputation: 79

How to get the length of material UI input filed in React JS?

I am trying to enable the button when the material input text length is more than 0.

This is a material input field component.

const MaterialInput = ({
    name,
    id = name,
    select,
    options = [],
    type,
    label,
    shrink,
    formik,
    disabled,
    handleClick,
}) => {
    return (
        <TextField
            type={type}
            name={name}
            label={label}
            select={select}
            autoComplete='off'
            variant='outlined'
            disabled={disabled}
            className='material-input'
            value={get(formik.values, name, '')}
            onBlur={formik.handleBlur}
            onChange={formik.handleChange}
            helperText={get(formik.touched, name) && get(formik.errors, name)}
            error={get(formik.touched, name) && Boolean(get(formik.errors, name))}
            InputLabelProps={{ shrink }}
        >
            {options.map((item) => (
                <MenuItem
                    onClick={handleClick}
                    className='text-capitalize'
                    value={item.value}
                    key={item.value}
                    disabled={item.disabled || false}
                >
                    {item.label}
                </MenuItem>
            ))}
        </TextField>
    );
};

This is how I am using it in other components.

aComponent.js

                <MaterialInput name={inputName} label={label} formik={typeofForm} />

How to Enable button when the length of text field is more than 0.

Upvotes: 1

Views: 803

Answers (3)

Mayank Narula
Mayank Narula

Reputation: 409

you can use what you pass to value prop in TextField and get its length

const getInputLength = (formik, name) => {
    const value = get(formik.values, name, '');
    return value.length;
}

Upvotes: 0

Erfan HosseinPoor
Erfan HosseinPoor

Reputation: 1077

You must check your validation on textField onchange, in this case, that you use formik for your form, Formik main component has a a callback function validate, you can use this function to handle your validation,

example

<Formik
 validate={(values) => { // here check your validations and you have access to the values }}
 validateOnChange
 validateOnBlur
/>

Upvotes: 0

Ram
Ram

Reputation: 868

There are many other ways to achieve it.

For suppose you material input name is mobileNumber and formik submit logic in component.js you can write below snippet in ur aComponent.js

useEffect(() => {
        if (formik.values.mobileNumber.length === 0) {
            // do your disable logic here
        } else {
             // do your logic
        }
    }, [formik.values.mobileNumber]);

Upvotes: 3

Related Questions