1

There is input field (<TagInput>) to enter a tag from evergreen-ui library. Right now it creates a tag after pressing on Enter key.

I would like to remove this behaviour and create a tag only if the focus has been changed (onBlur) and it should ignore pressing on Enter key.

It seems that onKeyDown is not working properly, I still can create tag if I press on Enter key.


  const createPlaceholder = (arr) => {
    if (arr > 0) {
      return { placeholder: '' };
    } else {
      return { placeholder: 'Enter tag' };
    }
  }
  const [tagProps, setTagProps] = useState(createPlaceholder(task?.labels?.length));

  const handleChangeLabels = (values) => {
    var arr = values.map(v => {
      return { id: null, task: null, value: v }
    });
    arr = arr.length ? [arr[0]] : [];
    handleChangeAttribute(arr, 'labels');
    setTagProps(createPlaceholder(arr.length));
  }

  const handleChangeAttribute = (value, attr) => {
    const res = { ...task };
    res[attr] = value && value.trim && value.trim() == '' ? '' : value;
    setTask(res);
  };

  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      event.preventDefault();
    }
  };

  <TagInput
    inputProps={tagProps}
    values={value}
    onChange={handleChange}
    onKeyDown={handleKeyDown}
    onBlur={handleBlur}
  />
LDropl
  • 846
  • 3
  • 9
  • 25

1 Answers1

1

For that you can use the props "onKeyDownCapture".

You can also use the props addOnBlur to add the tag on changing focus instead of using the "onBlur" props

Here is an example of usage I made: https://codesandbox.io/s/practical-brook-350z2s?file=/index.js

If you want more info about the difference between "onKeyDownCapture" and "onKeyDown" here you go: In React, what is the difference between onKeyUp and onKeyUpCapture (and onKeyDown/Capture)?

William Scalabre
  • 635
  • 4
  • 13