Skip to content

Instantly share code, notes, and snippets.

@lucas-lm
Created February 29, 2020 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucas-lm/03cd82977740906f75f74f11c4520366 to your computer and use it in GitHub Desktop.
Save lucas-lm/03cd82977740906f75f74f11c4520366 to your computer and use it in GitHub Desktop.
Peculiar input react hook for forms
import { useState } from 'react'
class Input {
constructor(initialValue) {
this._initialState = {
value: initialValue,
isEmpty: initialValue.length === 0
}
const [ state, setState ] = useState(this._initialState)
this._state = state
this.setState = setState
for (let prop in state) {
Object.defineProperty(this, prop, {
get: function() {
return this._state[prop]
},
set: function(newValue) {
this.setState({...this._state, [prop]: newValue})
}
})
}
}
changeState = newState => {
this.setState({...this._state, ...newState})
}
handleChange = event => {
const { value } = event.target
console.log(value)
this.value = value
}
reset = () => {
this.setState(this._initialState)
}
}
const useFormInput = (initialValue) => {
const input = new Input(initialValue)
return input
}
export default useFormInput
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment