React Form submit example
Hello React - forms - using controlled components in a form. author(s): Ryan Vice
by Allie Yu
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
class TextBox extends React.Component{
render() {
return (
<input className='form-control'
name={this.props.name}
type='text'
value={this.props.value}
onChange={this.props.onChange}/>
)
}
}
class ExampleForm extends React.Component{
state = {
form: {
firstName: 'allie',
lastName: 'yu'
}
}
onChange = event => {
this.state.form[event.target.name] = event.target.value;
this.setState({form: this.state.form});
}
onSubmit = event => {
event.preventDefault();
alert('Form submitted. firstName: ' +
this.state.form.firstName +
', lastName: ' +
this.state.form.lastName);
}
render(){
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')
);