import React, {useReducer} from 'react'; import classnames from 'classnames'; import WarningIcon from '@moda/icons/warning-16'; import './EmailSignup.scss'; const emailValidator = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{1,}$/i; const regexp = new RegExp(emailValidator); const validateEmail = (email: string) => regexp.test(email); interface Props { gender: string; } interface State { email: string; selectedGender: string; error: string; } type Action = | {type: 'ChangeEmail'; email: string} | {type: 'ChangeGender'; gender: string} | {type: 'SetError'; error: string}; export const EmailSignup = (props: Props) => { const initialState: State = { email: '', selectedGender: props.gender, error: '' }; const reducer = (state: State, action: Action) => { switch (action.type) { case 'ChangeEmail': if (validateEmail(action.email)) { return {...state, email: action.email, error: ''}; } else { return {...state, email: action.email}; } case 'ChangeGender': return {...state, gender: action.gender}; case 'SetError': return {...state, error: action.error}; } }; const [state, dispatch] = useReducer(reducer, initialState); const handleSubmit = (event: React.FormEvent) => { event.preventDefault(); if (validateEmail(state.email)) { dispatch({type: 'ChangeEmail', email: ''}); /* TODO: POST email and gender to signup endpoint */ } else { dispatch({ type: 'SetError', error: 'Email is invalid. Please enter a valid email.' }); } }; return (
state.error !== '' && dispatch({type: 'SetError', error: ''}) } >
Join our list for daily style inspiration & first access to global fashion.
dispatch({type: 'ChangeGender', gender: 'women'})} > dispatch({type: 'ChangeGender', gender: 'men'})}>
) => dispatch({type: 'ChangeEmail', email: event.target.value}) } />
{state.error}
To opt-out of email sharing or to view our privacy policy click here.
); };