This is a solution to the Newsletter sign-up form with success message challenge on Frontend Mentor.
Users should be able to:
- Add their email and submit the form
- See a success message with their email after successfully submitting the form
- See form validation messages if:
- The field is left empty
- The email address is not formatted correctly
- View the optimal layout for the interface depending on their device's screen size
- See hover and focus states for all interactive elements on the page
- Vite
- Semantic HTML5 markup
- CSS custom properties
- Flexbox
- CSS Grid
- Mobile-first workflow
- React - JS library
Learnt how to call the input field when changes occur, check the email if it follows the regex pattern and updates the 'email' state with the current value of the input field:
const [email, setEmail] = useState("");
// checks whether email is valid
const [isValid, setIsValid] = useState(false);
const [modal, setModal] = useState(false);
/* Called when the email input field changes.
It checks the email if it follows the emailRegex pattern
and updates the 'email' state with the current value of the input field */
const getEmail = (event) => {
const emailRegex = /^\w+([\.%+-]?\w+)+@\w+([\.-]?\w+)+(\.\w{2,})+$/;
const valid = emailRegex.test(event.target.value);
setIsValid(valid);
setEmail(event.target.value);
};
/* checks if isValid is true and opens the modal if it is */
const openModal = () => {
if (isValid && email !== "") setModal(true);
};
Learnt how to do conditional rendering of css classes:
<form onSubmit={onSubmit} className={isValid ? "" : "formInvalid"}>
<label htmlFor="email">Email address</label>
<input
className={isValid ? "valid" : "invalid"}
onChange={getEmail}
value={email}
type="email"
id="email"
placeholder="[email protected]"
title="Please enter a valid email address"
/>
<button onClick={openModal}>Subscribe to monthly newsletter</button>
</form>
Opened the Modal component using state and passed props to the component:
{
modal && <Modal closeModal={setModal} email={email} />;
}
Not completely used to React Hooks so going to continue my learning React journey.
- ChatGPT
- Deploying a Static site - This helped me deploy my website.
- Modal in ReactJS - Code a React Modal Tutorial using Hooks - This is helped me learn how to open a modal from a component using a button
- Frontend Mentor - @Fejiro001
- Twitter - @aberefejiro