基于React Bootstrap与EmailJs实现表单提交成功后的Toast/Modal提示功能
Custom Toast/Modal for Form Submission Success
Got it, let's get your custom toast/modal working properly! You're already on the right track with the showModal state—here's how to adjust your code to match your desired styling and fix a couple of React-specific details:
Key Adjustments:
- Swapped out the Bootstrap modal markup for your custom
<div className="toast_modal">container (you can style this in your CSS to act as either a toast or centered modal) - Fixed the button's
classattribute toclassName(React usesclassNameinstead ofclassfor DOM elements) - Added a dedicated
handleCloseModalfunction to properly hide the notification when the user clicks "Close" - Kept your exact success message as requested
Updated Full Code:
import { useState } from 'react'; import emailjs from 'emailjs-com'; const NameForm = () => { const [showModal, setShowModal] = useState(false); const sendEmail = (e) => { e.preventDefault(); emailjs.sendForm('service_ID', 'template_ID', e.target, 'user_ID') .then((result) => { console.log(result.text); setShowModal(true); }, (error) => { console.log(error.text); }); e.target.reset(); }; // Handle closing the toast/modal const handleCloseModal = () => { setShowModal(false); }; return ( <div> <h1 className="text-center text-md-left mb-3">Get in Touch</h1> <form className="contact-form" onSubmit={sendEmail}> <div className="form-group mb-0 py-3"> <textarea className="form-control custom--fields-mod text-the-primary" id="message" rows="3" placeholder="Message *" name="message" required ></textarea> </div> <div className="form-group row py-2 mb-0"> <div className="col-md-6 text-center text-md-left py-2 py-md-0"> <input className="buttons-width float-md-right btn btn-dark-moderate-orange rounded-0" type="submit" value="SEND MESSAGE" /> </div> </div> </form> {/* Your Custom Toast/Modal */} {showModal && ( <div className="toast_modal"> <div className="modal-body text-center py-4"> <p>We've received your inquiry, we'll get back to you as soon as possible. Thank you!</p> <button type="button" className="btn btn-dark-moderate-orange px-5" onClick={handleCloseModal} > Close </button> </div> </div> )} </div> ); }; export default NameForm;
Extra Tips:
- If you want a toast that auto-closes, add a timeout in the success handler:
.then((result) => { console.log(result.text); setShowModal(true); setTimeout(handleCloseModal, 5000); // Auto-close after 5 seconds }, (error) => { console.log(error.text); }); - Style your
.toast_modalclass in CSS to control positioning (e.g., fixed top-right for a toast, full-screen overlay with centered content for a modal), background color, padding, and animations.
内容的提问来源于stack exchange,提问作者clarkf
相关产品推荐
相关产品推荐

