Reputation: 27
I am attempting to use emailJS in a React Modal I have created. The modal was working just fine but the action is not. Below is my Email Component that gives me a console error of 'handleChange is not defined' in the console upon clicking the Modal. However, I have defined it on line 18.
import React from 'react';
import emailjs from 'emailjs-com';
export default class ContactUs extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
phone: '',
email: '',
message: ''
};
this.handleChange = handleChange.bind(this);
this.handleSubmit = handleSubmit.bind(this);
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = (e) => {
e.preventDefault();
emailjs
.sendForm(
'gmail',
'portfoliotemplate',
'.contact_form_class',
'user_wQPetSHncS1Xuyip0lihm'
)
.then()
.catch();
this.setState({
name: '',
phone: '',
email: '',
message: ''
});
};
render() {
return (
<div>
<form
onSubmit={this.handleChange}
className='contact-form'
>
<label>Name : </label>
<input
type='text'
id='name'
name='name'
placeholder='Your name'
value={this.state.name}
onChange={this.handleChange}
/>
<br />
<label>Phone : </label>
<input
type='number'
id='phone'
name='phone'
placeholder='Your phone number'
value={this.state.phone}
onChange={this.handleChange}
/>
<br />
<label>Email : </label>
<input
type='text'
id='email'
name='email'
placeholder='Your email'
value={this.state.email}
onChange={this.handleChange}
/>
<br />
<label>Message : </label>
<input
type='textarea'
id='message'
name='message'
placeholder='How may I be of assistance?'
value={this.state.message}
onChange={this.handleChange}
/>
<input
type='submit'
/>
</form>
</div>
);
}
}
Any feedback or suggestions would be greatly appreciated.
Upvotes: 0
Views: 4628
Reputation: 14365
Your issue is with these lines:
this.handleChange = handleChange.bind(this);
this.handleSubmit = handleSubmit.bind(this);
You missed the this
before your binding statements. That means handleChange
is undefined, so your binding is actually causing this.handleChange
to be undefined as well.
To reference a class method, you would need to change it to this.handleChange.bind(this)
.
However, the binding is unnecessary since you are using arrow syntax. Class methods defined using arrow syntax will get this
from scope, instead of by the context of the method call. So the easiest solution is to just remove the binds.
Upvotes: 4
Reputation: 1485
If you are using fat operator while declaring function handleChange and handleSubmit, than you should not bind that in constructor. So, remove binding from constructor and your constructor will be like as follows
constructor(props) {
super(props);
this.state = {
name: '',
phone: '',
email: '',
message: ''
};
// this.handleChange = handleChange.bind(this);
// this.handleSubmit = handleSubmit.bind(this);
}
Upvotes: 1