React Form submit example
Hello React - forms - using controlled components in a form.
author(s):
Ryan Vice
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://fb.me/react-with-addons-0.14.0.js"></script>
<script src="https://fb.me/react-dom-0.14.0.js"></script>
<div id="view"/>
CSS
button {
margin-left: 5px;
}
input {
margin: 5px;
}
form {
padding-right: 10px;
}
}
Babel + JSX
var TextBox = React.createClass({
render: function() {
return (
<input className='form-control'
name={this.props.name}
type='text'
value={this.props.value}
onChange={this.props.onChange}/>
);
}
});
var ExampleForm = React.createClass({
getInitialState: function () {
return { form: { firstName: 'Ryan', lastName: 'Vice'} }
},
onChange: function(event) {
this.state.form[event.target.name] = event.target.value;
this.setState({form: this.state.form});
},
onSubmit: function(event) {
event.preventDefault();
alert('Form submitted. firstName: ' +
this.state.form.firstName +
', lastName: ' +
this.state.form.lastName);
},
onKeyPress: function(e){
//alert(e);
if(e.keyCode === 13){
console.log(e.keyCode);
e.preventDefault();
}
},
render: function() {
var self = this;
return (
<form onSubmit={this.onSubmit} >
<TextBox name='firstName'
value={this.state.form.firstName}
onChange={this.onChange}/>
<TextBox name='lastName'
value={this.state.form.lastName}
onChange={this.onChange}/>
<button className='btn btn-success'
type='submit'>Submit</button>
</form>
);
}
});
ReactDOM.render(
<ExampleForm/>,
document.getElementById('view'));