React Form example with Controlled Components
React Form example with Controlled Components
React Form example with Controlled Components
Html:
1 |
<div id="app"></div> |
Css:
1 2 3 4 5 6 7 |
body { padding: 30px 20%; } h1 { font-size: 2em; text-align: center; } |
Js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
//Form component class ContactForm extends React.Component { constructor(props) { super(props); this.state = { name: '', email:'' }; this.handleChange = this.handleInputChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleInputChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); console.log('Change detected. State updated' + name + ' = ' + value); } handleSubmit(event) { alert('A form was submitted: ' + this.state.name + ' // ' + this.state.email); event.preventDefault(); } render() { return ( <div> <form onSubmit={this.handleSubmit} > <div className="form-group"> <label for="nameImput">Name</label> <input type="text" name="name" value={this.state.name} onChange={this.handleChange} className="form-control" id="nameImput" placeholder="Name" /> </div> <div className="form-group"> <label for="emailImput">Name</label> <input name="email" type="email" value={this.state.email} onChange={this.handleChange} className="form-control" id="emailImput" placeholder="email@domain.com" /> </div> <input type="submit" value="Submit" className="btn btn-primary" /> </form> </div> ) } } class MainTitle extends React.Component { render(){ return( <h1>React Form example</h1> ) } } class App extends React.Component { render(){ return( <div> <MainTitle/> <ContactForm/> </div> ) } } React.render(<App/>, document.getElementById('app')) |
Source: https://codepen.io/jonvadillo/pen/owzYQp