dokgu
dokgu

Reputation: 6050

Shift + Enter only for desktop

I have a React chat application where I use a textarea for the message input because I need multiline support. On mobile this works perfectly because when the user presses Enter, it starts a new line. There is a dedicated button to send the message once the user finishes writing their message.

On desktop however, I'd like this to be different. I want the user to have to press Shift + Enter to create a new line. If they only press Enter I want the message to send.

I found this tutorial which I think I can make work (I haven't added it in yet) but this means for users on their mobile devices, they will be unable to write multiline messages.

How do I go about doing this so that for users on mobile devices, pressing Enter on the textarea will start a new line but for users on mobile, it'll submit the form and they'd need to hold Shift + Enter to start a new line?

Upvotes: 0

Views: 252

Answers (1)

Umer Abbas
Umer Abbas

Reputation: 1876

I tried to create this functionality by detecting mobile device by it's touch screen feature. Here is working solution codesandbox

import "./styles.css";

export default function App() {
  const isTouchScren = () => {
    if (window.matchMedia("(pointer: coarse)").matches) {
      return true;
    }
    return false;
  };

  const onKeyPress = (event) => {
    if (
      (isTouchScren() && event.keyCode === 13 && !event.shiftKey) ||
      (event.keyCode === 13 && event.shiftKey)
    ) {
      // next line
      alert("next line");
    } else if (event.keyCode === 13 && !event.shiftKey) {
      // send text
      alert("send text");
    }
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <textarea onKeyDown={onKeyPress} rows={4} cols={50}>
        Start editing to see some magic happen!
      </textarea>
    </div>
  );
}

Upvotes: 1

Related Questions