Reputation: 273
So I was using a Material-UI autocomplete with "free solo" set to true, and trying to limit the number of characters you can enter.
Just for reference, that's using "@material-ui/core": "^4.10.0", "@material-ui/lab": "^4.0.0-alpha.54",
I tried adding maxLength to InputProps on the inner TextField as an attribute with no joy. I decided to post the answer, which I figured out, because it's NOT OBVIOUS.
Upvotes: 8
Views: 13555
Reputation: 28
in the new version of material ui (v6) inputProps prop is deprecated and will be removed in v7. Use slotProps.htmlInput
<TextField
label='text label'
slotProps={{
htmlInput: {
maxLength: 50,
},
}}
/>
Upvotes: 0
Reputation: 273
<Autocomplete
freeSolo
options={
optionType === "alpha"
? alpha_options.map((option) => option.behavior)
: beta_options.map((option) => option.behavior)
}
onInputChange={(event, value) => {
setBehavior(value);
}}
renderInput={(params) => (
<TextField
{...params}
className={classes.input}
inputProps={{ ...params.inputProps, maxLength: process.env.REACT_APP_ENTRY_MAX_LENGTH}}
autoFocus={false}
margin="dense"
id="behavior"
label="Behavior"
placeholder="Complete this sentence"
type="text"
variant="outlined"
fullWidth
/>
)}
/>
Here are the CRUCIAL TRUTHS:
1) InputProps and inputProps are NOT the same thing. From the MUI docs on TextField....
Yes, I know this is incredibly stupid and frustrating.
2) In an AutoComplete, the TextField is a child component of the AutoComplete itself. In order to preserve that sweet, sweet AutoComplete functionality goodness, you have to pass the AutoComplete's inputProps down to the TextField.
Hence this line:
inputProps={{ ...params.inputProps, maxLength: process.env.REACT_APP_ENTRY_MAX_LENGTH}}
That is, using the spread operator, grab all the inputProps in the params, and spread 'em into the TextField's inputProps, then add to it with maxLength. That process.env value is just one stored in my create-react-app's .env file.
You're welcome.
Upvotes: 13