Skip to content
Advertisement

How to limit a textarea to 4 rows of bullet points?

I was wondering if it is possible to limit a user to only enter 4 lines in a text area. I have tried using maxRows, but that isn’t working as I thought. Notice how I have put maxLength to 9999999, as I don’t mind how much text is entered on each bullet point, I just want to limit it to a maximum of 4 new line characters/bullet points. If anyone has a solution to how I could accomplish this, that would be great.

<TextField
        onKeyUp={handleInput}
        inputProps={{
          maxLength: 9999999
        }}
        sx={{ ...fieldCSS, width: '100%', marginTop: '6px' }}
        multiline
        rows={4}
        value={details}
        onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
          setDetails(event.target.value);
          setCalled({ ...called, detail: true });
        }}
        error={!canSubmitDetails && called.detail}
        helperText={detailsHelperText}
      />

See in the image below, I dont want the user being able to enter that 4th bullet point. enter image description here

EDIT: after adding the suggested answer with a minor edit but event.stopPropagation(); isnt working

  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    const { code, target } = event;
    const { value } = target as HTMLInputElement;

    if (code === 'Enter') {
      if ([...value].filter((word) => word === 'n').length >= DETAIL_MAX_LINES) {
        event.stopPropagation();
      }
    }
  };

Cheers, Has400

Advertisement

Answer

You can use the onKeyDown event to check if the user is pressing the enter key. If so, you can check if the number of lines is equal to 4. If so, you can prevent the default behavior of the enter key.

const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
  if (event.key === 'Enter') {
    const lines = event.currentTarget.value.split('n');
    if (lines.length === 4) {
      event.preventDefault();
    }
  }
};

<TextField
  onKeyDown={handleKeyDown}
  ...
/>

EDIT: It doesn’t look like the enter key method is working, so try using the onChange event to check if the number of lines is greater than 4.

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  const { value } = event.target;

  if ([...value].filter((word) => word === 'n').length >= 4) {
    event.stopPropagation();
  }
};
<TextField
        onChange={handleChange}
        ...
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement