Reputation: 391
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
Submit the form with Enter Key without refreshing the page and adding the button element.
import React, {useState, useRef} from 'react';
export const AppHomeFeedPage = () => {
const [values, setValues] = useState(NewPostsInitialValues);
const Avatar = UserAvatar
const ref = useRef();
function changeHandler (event) {
setValues({
...values,
[event.target.name]: event.target.value
});
console.log(values)
}
const onSubmitForm = (e) => {
e.preventDefault();
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 )
}
return(
<div className='AppHomePageContentContainer'>
<div className="AppMainContentWrapper">
<form className='NewPostForm' ref={ref} onKeyUp={onSubmitForm} tabIndex={0}>
<div className="NewPostCardContainer">
<div className="NewPostCardContainerWrapper">
<div className="NewPostCardTopWrapper">
<div className="NewPostCarUserAvatarContainer">
<div className="NewPostCarUserAvatarWrapper">
<img className='NewPostCarUserAvatar' src={Avatar} alt="user image"/>
</div>
</div>
<div className="NewPostCardInputContainer">
<div className="NewPostCardInputWrapper">
<textarea
name='postText'
className="NewPostTextArea"
placeholder={`How's your Portfolio Today ?`}
// id='quoteTypeLabelContainer'
value={values.postText}
onChange={changeHandler}
/>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
)
}
Upvotes: 0
Views: 2156
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