Put length contraint in a TextField in react js

You can set the maxLength property for limiting the text in text box.

Instead of onChange method you can pass maxLength to the inputProps props of material-ui TextField.

<TextField
    required
    id="required"
    label="Required"
    defaultValue="Hello World"
    inputProps={{ maxLength: 12 }}
/>

Basically we can edit all input element's native attrs via inputProps object.

Link to TextField Api


I found another solution here.

<TextField
    required
    id="required"
    label="Required"
    defaultValue="Hello World"
    onInput = {(e) =>{
        e.target.value = Math.max(0, parseInt(e.target.value) ).toString().slice(0,12)
    }}/>

      <TextField
        id="username"
        name="username"
        label={translate('username')}
        onChange={handleChange}
        onBlur={handleBlur}
        value={values.username}
        error={Boolean(errors.username) && touched.username}
        helperText={(errors.username && touched.username && translate(errors.username))}
        required
        inputProps={{maxLength :20}}

      />