Skip to content

Instantly share code, notes, and snippets.

@aerrity
Last active November 20, 2020 10:39
Show Gist options
  • Select an option

  • Save aerrity/07ca40d42af5a8db48e0e3d974466ed1 to your computer and use it in GitHub Desktop.

Select an option

Save aerrity/07ca40d42af5a8db48e0e3d974466ed1 to your computer and use it in GitHub Desktop.
React controlled component (form) with multiple inputs example
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