Tayyab Rahman
Tayyab Rahman

Reputation: 391

Submit From with Enter key without refreshing the page in React

I want to submit From (Textarea) values with Enter key and without refreshing the page. I also do not want to show the submit button. Using the code below, but on Enter, it refreshes the page. Help will be appreciated.

Current Behaviour

Required Behaviour

Upvotes: 0

Views: 2156

Answers (1)

Matthew Kwong
Matthew Kwong

Reputation: 2947

Use onSubmitForm as an onSubmit listener instead of onKeyUp. Most browsers will treat pressing enter in a form as submit action.

i.e.

<form onSubmit{onSubmitForm} />
const onSubmitForm = e => {
  e.preventDefault();

  // Since this is not a keyUp event, you don't need this part
  // if (e.keyCode === 13 || e.keyCode === 'Enter') {
  //   ref.current.submit();
  // }

  let userId = values.userId;
  let userName = values.userName;
  let postText = values.postText;
  console.log(userId, userName, postText)

  // HTTP request submit form, modify it depending on your need
  fetch('/api/form', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ userId, userName, postText })
  });
};

Upvotes: 1

Related Questions