Skip to content

[Note] React Dev Notes: Enter to submit form and Input autofocus

Today I made some minor UX tweaks and just took the code snippet as my dev notes as below.

I forgot to add press Enter to submit form, so before this fix user need to hand on their mouse again and click the submit button 😒

To implement press Enter to submit form, with React and Ant Design:

function myFunc() {
  // do something
}

<Input
    placeholder="xxx"
    value={message}
    onChange={(e) => setMessage(e.target.value)}
    onPressEnter={myFunc} {/*  Add this Line! */}
    ref={myInput}
/>

Another UX fix is to auto focus on this input box after page load. This can be done by:

const myInput = useRef(null);

useEffect(() => {
  if (myInput.current) {
    myInput.current.focus();
  }
}, [myInput]);

<Input
    placeholder="xxx"
    value={message}
    onChange={(e) => setMessage(e.target.value)}
    onPressEnter={myFunc}
    ref={myInput} {/*  Add this Line! */}
/>

Leave a Reply

Your email address will not be published. Required fields are marked *