Let's start by creating a custom dataset generic type that extends the native dataset type.
export type DatasetInjector<T, D extends DOMStringMap> = T & {
dataset: D;
};
Now to showcase above custom generic let's assume I've two inputs (input, textaera) and each have custom attribute inputId
. This is to identify which the input called the on change handler when we entered the password or confirm password.
const Input = () => {
const [value, setValue] = React.useState({
password: '',
confirmPassword: '',
});
const changeHandler: ChangeEventHandler<
DatasetInjector<HTMLInputElement, { inputId: string }>
> = (e) => {
setValue((prevState) => ({
...prevState,
[e.target.dataset.inputId]: e.target.value,
}));
};
const textareaChangeHandler: ChangeEventHandler<
DatasetInjector<HTMLTextAreaElement, { inputId: string }>
> = (e) => {
setValue((prevState) => ({
...prevState,
[e.target.dataset.inputId]: e.target.value,
}));
};
return (
<>
<input
data-input-id='password'
onChange={changeHandler}
value={value.password}
/>
<textarea
data-input-id='confirmPassword'
onChange={textareaChangeHandler}
value={value.confirmPassword}
/>
</>
);
};
For more info see my article here Reference link
const element = event.target as HTMLElement;
work? (you would then have to doconst cityName = element.dataset.value;
)