Last active
June 9, 2021 12:53
-
-
Save hemepositive/5d6b262191cd84d86edf0b31ee97f4ce to your computer and use it in GitHub Desktop.
React Generic Change Handlers
This file contains 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
// 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