React setter function

September 04, 2021

1 min read

views

Implementation

src/lib/setter.ts
import type * as React from "react";

type Set<T> = React.Dispatch<React.SetStateAction<T>>;
type ChangeEvent<E> = React.ChangeEvent<E>;
type Input = HTMLInputElement | HTMLTextAreaElement;

export function setter<T extends number | string | Date, E extends Input = HTMLInputElement>(
  setX: Set<T>,
) {
  return (e: ChangeEvent<E>) => {
    setX(e.target.value as T);
  };
}

Usage

import { setter } from "lib/setter";

const Component = () => {
  const [name, setName] = React.useState<string>("");

  return <input id="name-input" value={name} onChange={setter(setName)} />;
};