Last active
September 3, 2020 17:35
-
-
Save awave1/20509792b20be23721dcb777ffa9808c to your computer and use it in GitHub Desktop.
Simple generic function for setting values on change when using `useState` hook
This file contains hidden or 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
// example usage | |
import React from 'react'; | |
enum SelectVal { | |
ONE, | |
TWO, | |
THREE | |
} | |
export default function Form() { | |
const [name, setName] = React.useState(''); | |
const [val, setVal] = React.useState(SelectVal.ONE); | |
return ( | |
<form> | |
<input | |
type="text" | |
onChange={onInputChange(setName)} | |
/> | |
<select | |
onChange={onInputChange<SelectVal>(setVal)} | |
value={val} | |
> | |
<option ...> | |
</select> | |
</form> | |
); | |
} |
This file contains hidden or 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
function onInputChange<T>(setter: Dispatch<SetStateAction<T>>) { | |
return ({ | |
target: { value }, | |
}: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => { | |
// In order to cast `value` to generic type T, cast it to `unknown` first | |
setter((value as unknown) as T); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Applicable for inputs and selects