React setter function

Published 14 days ago - 1 min read

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 const setter =
  <T, E extends Input = HTMLInputElement>(setX: Set<T>) =>
  (e: ChangeEvent<E>) => {
    const value = e.target.value;

    setX(value as unknown 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)} />;
};