Пожалуйста, не забудьте добавить ошибки, которые вы получаете, или в какой момент ваш код перестает работать, чтобы мы могли лучше понять, что не так.
Я уже вижу несколько вещей в вашем коде, я Я исправлю их ниже и напишу большой комментарий над каждым исправлением, чтобы вы могли определить, где я изменил код.
const [values, setValues] = useState({
name: '',
email: '',
message: '',
});
const handleChange = (name)=> (e) => {
setValues({ ...values, [e.target.id]: e.target.value });
};
const isFormValid = () => {
if (!values.name || !values.email || !values.message) {
return false;}
else {
return true;}
};
const sendEmail = (e) => {
emailjs.sendForm('gmail', 'template_AILAIHUt', e.target, 'user_kPqhCaNpQHv75H92RjVhj')
.then((result) => {
console.log(result.text + 'funciona');
}, (error) => {
console.log(error.text + 'no funciona');
});
}
const handleSubmit = (e) => {
// HERE: you always want to prevent default, so do this first
e.preventDefault()
if (!isFormValid()) {
//message of error in the screen, maybe sweet alerts
console.log('falta algo')
} else{
sendEmail(e)
}
};
return (
<div className={classes.section}>
<div className={classes.container}>
<GridContainer justify="center">
<GridItem xs={12} sm={12} md={4}>
<Card>
<!-- HERE: use the FORM submit function and make sure to pass the event down to handleSubmit(e)@ -->
<form className={classes.form} onSubmit={(e) => handleSubmit(e)}>
<CardHeader style={{ fontWeight: "fontWeightBold" }} color='primary' className={classes.cardHeader}>
<h4>Let's create something together </h4>
</CardHeader>
<CardBody>
<CustomInput
labelText="Name..."
id="name"
required={true}
formControlProps={{
required: true,
fullWidth: true
}}
inputProps={{
required: true,
onChange: handleChange(),
id:'name',
value: values.name,
type: "text",
endAdornment: (
<InputAdornment position="end">
<People className={classes.inputIconsColor} />
</InputAdornment>
)
}}
/>
<CustomInput
labelText="Email..."
id="email"
type='email'
required={true}
onChange={handleChange()}
formControlProps={{
required: true,
fullWidth: true
}}
inputProps={{
required: true,
onChange: handleChange(),
id:'email',
value: values.email,
type: "email",
endAdornment: (
<InputAdornment position="end">
<Email className={classes.inputIconsColor} />
</InputAdornment>
)
}}
/>
<CustomInput
labelText="Be free..."
id="message"
required={true}
formControlProps={{
size: 'large',
rows: '4',
required: true,
fullWidth: true
}}
inputProps={{
multiline: true,
required: true,
onChange: handleChange(),
id:'message',
value: values.message,
multiline: true,
type: "text",
endAdornment: (
<InputAdornment position="end">
<Icon className={classes.inputIconsColor}>
<SendIcon className={classes.inputIconsColor}/>
</Icon>
</InputAdornment>
),
autoComplete: "off"
}}
/>
</CardBody>
<CardFooter className={classes.cardFooter}>
<input type="submit" value="Submit" />
</CardFooter>
</form>
</Card>
</GridItem>
</GridContainer>
</div>
</div>
);
}
Самый большой отвод, пока вы немного путаете форму logi c. Форма опирается на кнопку отправки, которая имеет тип ввода. Кроме того, используйте функцию onSubmit вместе с элементом ввода submit.
Если вы хотите работать с формой и предотвращать событие отправки по умолчанию, вы должны использовать кнопку отправки типа ввода и onSubmit
функция формы. Поскольку это приложение реакции, и вы вообще не полагаетесь на события формы, вы также можете сделать это по-другому (и сохранить свою стилизованную кнопку). См. это руководство о том, как отправить форму с помощью пользовательской кнопки.