У меня есть компонент формы для сбора email адресов. Как сделать, если форма отправлена, скрыть форму и вывести сообщение об успешной отправке? и добавить отправку данных на сервер?
import React, { Component } from 'react';
import { FormErrors } from '../components/FormsErrors';
class SubscibeFrom extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
formErrors: { email: ''},
emailValid: false,
formValid: false
}
}
handleUserInput = (e) => {
const name = e.target.name;
const value = e.target.value;
this.setState({ [name]: value },
() => { this.validateField(name, value) });
}
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
switch (fieldName) {
case 'email':
emailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.email = emailValid ? '' : ' is invalid';
break;
default:
break;
}
this.setState({
formErrors: fieldValidationErrors,
emailValid: emailValid,
}, this.validateForm);
}
validateForm() {
this.setState({ formValid: this.state.emailValid && this.state.passwordValid });
}
errorClass(error) {
return (error.length === 0 ? '' : 'has-error');
}
render() {
return (
<form className="demoForm mb-10">
<div className="panel panel-default">
<FormErrors formErrors={this.state.formErrors} />
</div>
<div className={`form-group ${this.errorClass(this.state.formErrors.email)}`}>
<label htmlFor="email">Email address</label>
<input type="email" required className="form-control" name="email"
placeholder="Email"
value={this.state.email}
onChange={this.handleUserInput} />
</div>
<button type="submit" className="btn btn-primary" disabled={!this.state.formValid}>Send</button>
<div className='form-success'>
<div className='form-success__title'>
<h2>Thank you for subscribing!</h2>
</div>
<div className='form-success__text'>
<p>We will send you a confirmation email shortly.</p>
</div>
</div>
</form>
)
}
}
export default SubscibeFrom;