When a user submits a message to the message board, The User input still remains after posting. What syntax can I implement that will clear the input fields upon submission?
import { Card, Container, Form, Button } from "react-bootstrap";
import Label from "react-bootstrap/Card";
import React, { useState } from "react";
export default function MessageForm({handleAddPost}) {
const [formData, setFormData] = useState({
photo: '',
title: '',
content: ''
})
function handleChange(evt) {
setFormData({...formData, [evt.target.name]: evt.target.value});
}
function handleSubmit(e) {
e.preventDefault();
handleAddPost(formData);
}
return (
<Container>
<Card className="text-center" border="success" style={{ width: '85vw' }}>
<Form size="sm" autoComplete="off" onSubmit={handleSubmit}>
<Label>Title</Label>
<Form.Control size="sm"
value={formData.title} name="title"
onChange={e => handleChange(e)}
/>
<Label>Message</Label>
<Form.Control size="sm"
value={formData.content} name="content"
onChange={e => handleChange(e)}
/>
<Button size="sm" variant="success" type="submit">Add Post</Button>
</Form>
</Card>
</Container>
);
}
CodePudding user response:
You can do something like
import { Card, Container, Form, Button } from "react-bootstrap";
import Label from "react-bootstrap/Card";
import React, { useState } from "react";
const initialState = {
photo: '',
title: '',
content: ''
};
export default function MessageForm({handleAddPost}) {
const [formData, setFormData] = useState(initialState);
function handleChange(evt) {
setFormData({...formData, [evt.target.name]: evt.target.value});
}
async function handleSubmit(e) {
e.preventDefault();
await handleAddPost(formData);
setFormData(initialState);
}
return (
<Container>
<Card className="text-center" border="success" style={{ width: '85vw' }}>
<Form size="sm" autoComplete="off" onSubmit={handleSubmit}>
<Label>Title</Label>
<Form.Control size="sm"
value={formData.title} name="title"
onChange={e => handleChange(e)}
/>
<Label>Message</Label>
<Form.Control size="sm"
value={formData.content} name="content"
onChange={e => handleChange(e)}
/>
<Button size="sm" variant="success" type="submit">Add Post</Button>
</Form>
</Card>
</Container>
);
}
CodePudding user response:
add this at the end handleSubmit
setFormData({
photo: '',
title: '',
content: ''
});