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
      autoFocus={true}
      name="name"
      onChange={handleChange}
      placeholder="placeholder"
      id="filled-basic"
      variant="filled"
      size="small"
      fullWidth
      inputProps={{
        maxLength: 25,
      }}
      InputProps={{
        startAdornment: (
          <InputAdornment position="start">
            <SearchIcon />
          </InputAdornment>
        ),
      }}
    />