React form onKeyDown event not working in mobile

155 views Asked by At
const handleTags = (e) => {
  if ((e.key === "Enter" || e.keyCode === 13) && e.target.value.trim() !== "") {
    e.preventDefault(); // Prevent form submission
    e.stopPropagation(); // Prevent event bubbling
    setTags([...tags, e.target.value.trim()]);
    e.target.value = "";
  }
};
      <div className="form-group">
            <label htmlFor="tags">Tags</label>
            <input
              type="text"
              name="tags"
              autoComplete="off"
              placeholder="type a tag and press enter"
              onKeyDown={handleTags}
              id="tags"
              required
              className="form-control"
            />
          </div>

This is a function in react where as I type a tag in an input textbox, followed by the enter key, it gets added to the tag state. It works perfectly in desktop but on mobile, when I press the enter key the focus changes from the input text box to another form element and the function doesn't run as expected. only on mobile

1

There are 1 answers

4
Tom On

This may be linked to the fact that some mobile browsers interpret the "Enter" key differently, especially within forms.

Try blocking the behavior on mobile to see the reaction

    const handleTags = (e) => { if ((e.key === "Enter" || e.keyCode === 13) && e.target.value.trim() !== "") {e.preventDefault(); 
if (!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))) {
  e.stopPropagation();
}

setTags([...tags, e.target.value.trim()]);
e.target.value = ""; }};