can anyone help how to clear the text field after sending the message? I tried many approaches but it didn't work. I tried to use preventDefualt and setFirstname('') empty string but it didn't work also. thanks for helping , as I need to solve this issue
const [firstename, setFirstName] = useState('');
const [lastename, setLastName] = useState('');
const sendCollectionRef = collection(db, 'messages');
const [loader, setLoader] = useState(false);
const creatSend = async () => {
setLoader(true);
await addDoc(sendCollectionRef, {
Firstname: firstename,
Lastname: lastename,
Email: email,
Message: message,
})
.then(() => {
setLoader(false);
setLastName('');
alert('Your Message has been sent');
})
.catch((error) => {
alert(error.message);
setLoader(false);
});
};
<TextField
id="outlined-basic"
label="Message"
multiline
rows={4}
variant="outlined"
placeholder="Type Your Message"
fullWidth
style={{ backgroundColor: '#2b2b2b' }}
onChange={(event) => {
setMessage(event.target.value);
}}
/>
<Grid xs={12} item >
<LoadingButton
onClick={creatSend}
endIcon={<SendIcon />}
variant="contained"
style={{
background: loader ? '#ccc' : ' rgb(2, 2, 110)',
}}
CodePudding user response:
Usually, if you're not using a library to handle forms(e.g. formik), you have to bind each textfield value to a local state.
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
<TextField name="firstName" value={firstName} onChange={e => setFirstName(e.target.value) ...... />
<TextField name="lastName" value={lastName} onChange={e => setLastName(e.target.value) ...... />
Then in the submit handler, once you have sent your data to the server, you can reset the field values just changing the states:
setLastName('');
setFirstName('');