I am currently making a blog website with "reactjs".In this component, I am creating new blogs by putting values of author, title, and body. I cant submit the form by hitting 'Enter' on the keyboard on any fields.
This problem gets fixed when I remove my input field of author. Please guide me as I am new to Reactjs
import React, { useState } from "react"; function Create() { const [title, setTitle] = useState(); const [author, setAuthor] = useState(); const [body, setBody] = useState(); const submitFunc = (e) => { e.preventDefault(); const blog = { title, body, author }; }; return ( <div className="create container "> <form onSubmit={submitFunc}> <label className="text-danger" htmlFor="title"> Title: </label> <input name="title" type="text" onChange={(e) => setTitle(e.target.value)} required /> <label className="text-danger" htmlFor="body"> Content: </label> <textarea onChange={(e) => setBody(e.target.value)} required name="body" ></textarea> <label className="text-danger" htmlFor="author"> Author: </label> <input name="author" id="author" type="text" onChange={(e) => setAuthor(e.target.value)} required /> </form> <p>{title}</p> <p>{author}</p> <p>{body}</p> </div> ); } export default Create;
From the snippet you reported it is not clear how it should handle the Enter
pressing.
If you want to do anything when the user presses Enter
on any text area you can use the onKeyPress
event handler.
const handleKeyPress = (e) => {
if(e.keyCode === 13){
e.preventDefault();
// ...check title, boby and author exists
const blog = { title, body, author };
// ...submit the form
};
<textarea
name="body"
required
onChange={(e) => setBody(e.target.value)}
onKeyPress={handleKeyPress}
></textarea>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.