I'm learning reactjs and I have problem with my form.
I'm getting error from my console like this profile.js:54 Uncaught TypeError: Cannot read property 'target' of undefined
when I reload my page. Form is not rendering in my page, but I think this code should work.
my file profile.js:
var BasicInput = React.createClass({
render: function () {
return (
<input type="text" onChange={this.props.valChange} value={ this.props.val} />
);
}
});
var BasicForm = React.createClass({
getInitialState: function(){
return {
firstName: '',
lastName: ''
};
},
submit: function (e){
var self;
e.preventDefault()
self = this;
console.log(this.state);
var data = {
firstName: this.state.firstName,
lastName: this.state.lastName
};
// Submit form via jQuery/AJAX
$.ajax({
type: 'POST',
url: '/accounts/profile/details-form',
data: data
})
.done(function(data) {
self.clearForm()
})
.fail(function(jqXhr) {
console.log('failed to change basic info');
});
},
clearForm: function() {
this.setState({
firstName: "",
lastName: ""
});
},
firstnameChange: function(e){
this.setState({firstName: e.target.value});
},
lastnameChange: function(e){
this.setState({lastName: e.target.value});
},
render: function() {
return (
<form onSubmit={this.submit}>
<div className="form-half">
<BasicInput label="Firstname" valChange={this.firstnameChange()} val={this.state.firstName}/>
</div>
<div className="form-half">
<BasicInput label="Lastname" valChange={this.lastnameChange()} val={this.state.lastName}/>
</div>
<button type="submit">Submit</button>
</form>
);
}
});
ReactDOM.render(
<BasicForm />,
document.getElementById('basicInfoForm')
);
What is wrong in this code?
Many thanks for help with this problem.
You should pass reference to functions firstnameChange
and lastnameChange
but not call them (remove ()
from each of them)
<BasicInput
label="Firstname"
valChange={ this.firstnameChange }
val={ this.state.firstName }
/>
<BasicInput
label="Lastname"
valChange={ this.lastnameChange }
val={ this.state.lastName }
/>