import React, { Component } from 'react' import styled from 'styled-components' import { stringify } from 'qs' import { color } from '../globalStyles' const fetch = window.fetch class Form extends Component { state = { name: '', email: '', message: '', subject: `New Submission from ${this.props.siteTitle}!`, _gotcha: '', disabled: false, alert: '', action: '/contact/', 'form-name': 'Contact' } form = null componentDidMount () { Array.from(document.querySelectorAll('.Form .Input')).forEach(input => { input.addEventListener('invalid', () => { console.log(input) input.dataset.touched = true }) input.addEventListener('blur', () => { if (input.value !== '') input.dataset.touched = true }) }) } handleSubmit = (e) => { e.preventDefault() const data = { name: this.state.name, email: this.state.email, message: this.state.message, subject: this.state.subject, _gotcha: this.state._gotcha, 'form-name': this.state['form-name'] } this.setState({ disabled: true }) fetch(this.state.action + '?' + stringify(data), { method: 'POST' }) .then(res => { if (res.ok) { return res } else { throw new Error('Network error') } }) .then(res => { this.setState({ disabled: false, alert: 'Thanks for your enquiry, we will get back to you soon.', name: '', email: '', message: '', subject: `New Submission from ${this.props.siteTitle}!`, _gotcha: '' }) }) .catch(err => { console.log(err) this.setState({ disabled: false, alert: '❗️ There is a problem, your message has not been sent, please try contacting us via email' }) }) } handleChange = (e) => { this.setState({ [e.target.name]: e.target.value }) } render () { return ( { this.form = form }} className='Form' action={this.state.action} onSubmit={this.handleSubmit} data-netlify='' data-netlify-honeypot='_gotcha' > { this.state.alert && {this.state.alert} }