Created
February 29, 2020 21:33
-
-
Save lucas-lm/03cd82977740906f75f74f11c4520366 to your computer and use it in GitHub Desktop.
Peculiar input react hook for forms
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
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