Skip to content

Instantly share code, notes, and snippets.

@awave1
Last active September 3, 2020 17:35
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 awave1/20509792b20be23721dcb777ffa9808c to your computer and use it in GitHub Desktop.
Save awave1/20509792b20be23721dcb777ffa9808c to your computer and use it in GitHub Desktop.
Simple generic function for setting values on change when using `useState` hook
// 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>
);
}
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);
};
}
@awave1
Copy link
Author

awave1 commented Sep 3, 2020

Applicable for inputs and selects

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment