Skip to content

Instantly share code, notes, and snippets.

@nnaku
Created June 28, 2019 21:34
Show Gist options
  • Save nnaku/080060f9590775ce668031a8564918a9 to your computer and use it in GitHub Desktop.
Save nnaku/080060f9590775ce668031a8564918a9 to your computer and use it in GitHub Desktop.
import React, { useState } from 'react'
function Form() {
const [firstName, setFirstName] = useState('Maija')
const [lastName, setLastName] = useState('Mehiläinen')
function handleFirstNameChange(e) {
setFirstName(e.target.value)
}
function handleLastNameChange(e) {
setLastName(e.target.value)
}
return (
<div>
<input value={firstName} onChange={handleFirstNameChange} />
<input value={lastName} onChange={handleLastNameChange} />
</div>
)
}
export default Form
import React, { useState } from 'react'
// generic state for input
function useFormInput(initVal) {
const [value, setValue] = useState(initVal)
const handleChange = e => setValue(e.target.value)
return {
value,
onChange: handleChange
}
}
function Form() {
const firstName = useFormInput('Maija')
const lastName = useFormInput('Mehiläinen')
return (
<div>
<input {...firstName} />
<input {...lastName} />
</div>
)
}
export default Form
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment