Skip to content

Instantly share code, notes, and snippets.

@hemepositive
Last active June 9, 2021 12:53
Show Gist options
  • Save hemepositive/5d6b262191cd84d86edf0b31ee97f4ce to your computer and use it in GitHub Desktop.
Save hemepositive/5d6b262191cd84d86edf0b31ee97f4ce to your computer and use it in GitHub Desktop.
React Generic Change Handlers
// https://www.taniarascia.com/crud-app-in-react-with-hooks/
const handleInputChange = (event) => {
const { name, value } = event.target
setUser({ ...user, [name]: value })
}
===============================================================================================================
// !! https://www.pluralsight.com/guides/handling-multiple-inputs-with-single-onchange-handler-react
// https://hjnilsson.com/2016/12/11/generic-form-handleChange-in-react/
import React from 'react';
import TranslatedComponent from '../utils/TranslatedComponent.js';
class CreditCardForm extends React.Component {
constructor() {
super()
this.state = {
name: '',
address: '',
ccNumber: ''
}
}
handleChange(e) {
// If you are using babel, you can use ES 6 dictionary syntax
// let change = { [e.target.name] = e.target.value }
let change = {}
change[e.target.name] = e.target.value
this.setState(change)
}
render() {
return (
<form>
<h2>Enter your credit card details</h2>
<label>
Full Name
<input type="name" onChange={this.handleChange.bind(this)} value={this.state.name} />
</label>
<label>
Home address
<input type="address" onChange={this.handleChange.bind(this)} value={this.state.address} />
</label>
<label>
Credit card number
<input type="ccNumber" onChange={this.handleChange.bind(this)} maxlength="16" value={this.state.ccNumber} />
</label>
<button type="submit">Pay now</button>
</form>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment