I am running a Laravel 5 application that has its main view rendered using React.js. On the page, I have a simple input form, that I am handling with Ajax (sending the input back without page refresh). I validate the input data in my UserController. What I would like to do is display error messages (if the input does not pass validation) in my view.
I would also like the validation errors to appear based on state (submitted or not submitted) within the React.js code.
How would I do this using React.js and without page refresh?
Here is some code:
React.js code:
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var SignupForm = React.createClass({
getInitialState: function() {
return {email: '', submitted: false, error: false};
},
_updateInputValue(e) {
this.setState({email: e.target.value});
},
render: function() {
var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
return (
<div>
{this.state.submitted ? null :
<div className="overall-input">
<ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
<input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} />
<div className="button-row">
<a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
</div>
</ReactCSSTransitionGroup>
</div>
}
</div>
)
},
saveAndContinue: function(e) {
e.preventDefault()
if(this.state.submitted==false) {
email = this.refs.email.getDOMNode().value
this.setState({email: email})
this.setState({submitted: !this.state.submitted});
request = $.ajax({
url: "/user",
type: "post",
data: 'email=' + email + '&_token={{ csrf_token() }}',
data: {'email': email, '_token': $('meta[name=_token]').attr('content')},
beforeSend: function(data){console.log(data);},
success:function(data){},
});
setTimeout(function(){
this.setState({submitted:false});
}.bind(this),5000);
}
}
});
React.render(<SignupForm/>, document.getElementById('content'));
UserController:
public function store(Request $request) {
$this->validate($request, [
'email' => 'Required|Email|Min:2|Max:80'
]);
$email = $request->input('email');;
$user = new User;
$user->email = $email;
$user->save();
return $email;
}
Thank you for your help!