Skip to content

Instantly share code, notes, and snippets.

@mitchallen
Last active December 16, 2021 21:21
Show Gist options
  • Save mitchallen/9effb6373eaa2780340b6fb60a80f079 to your computer and use it in GitHub Desktop.
Save mitchallen/9effb6373eaa2780340b6fb60a80f079 to your computer and use it in GitHub Desktop.
// File: UsedCheckedInput.tsx
// Author: Mitch Allen
import {ChangeEventHandler, useCallback, useState} from "react";
export interface CheckedInput {
id?: string,
name?: string,
init?: boolean,
}
export interface CheckedInputProps {
id?: string,
name?: string,
checked: boolean,
setChecked: any,
onChange: ChangeEventHandler<HTMLTextAreaElement | HTMLInputElement> | undefined,
}
export function useCheckedInput(options: CheckedInput = {}): CheckedInputProps {
let {
id = undefined,
name = undefined,
init = false,
} = options;
if (name === undefined) {
name = id;
}
const [checked, setChecked] = useState(init);
const onChange = useCallback((event) => {
// Note that this is returning 'checked':
setChecked(event.target.checked);
}, []);
return {
id,
name,
checked,
setChecked,
onChange,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment