Last active
November 20, 2020 10:39
-
-
Save aerrity/07ca40d42af5a8db48e0e3d974466ed1 to your computer and use it in GitHub Desktop.
React controlled component (form) with multiple inputs example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react'; | |
| import ReactDOM from 'react-dom'; | |
| class SignUp extends React.Component { | |
| constructor(props) { | |
| super(props); | |
| this.state = { | |
| newsLetter: true, | |
| email: '' | |
| }; | |
| this.handleInputChange = this.handleInputChange.bind(this); | |
| } | |
| handleInputChange(event) { | |
| const target = event.target; | |
| const value = target.type === 'checkbox' ? target.checked : target.value; | |
| const name = target.name; | |
| console.log(`Input name ${name}. Input value ${value}.`); | |
| this.setState({ | |
| [name]: value | |
| }); | |
| } | |
| render() { | |
| return ( | |
| <form> | |
| <label> | |
| I wish to receive your email newsletter. | |
| <input | |
| name="newsLetter" | |
| type="checkbox" | |
| checked={this.state.newsLetter} | |
| onChange={this.handleInputChange} /> | |
| </label> | |
| <br /> | |
| <label> | |
| Email: | |
| <input | |
| name="email" | |
| type="text" | |
| value={this.state.email} | |
| onChange={this.handleInputChange} /> | |
| </label> | |
| </form> | |
| ); | |
| } | |
| } | |
| ReactDOM.render( | |
| <SignUp />, | |
| document.getElementById('root') | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment