Skip to content

Instantly share code, notes, and snippets.

@maladr0it
Created October 21, 2019 02:39
Show Gist options
  • Select an option

  • Save maladr0it/38d41b2153abd4ff6aed0d19ec96059b to your computer and use it in GitHub Desktop.

Select an option

Save maladr0it/38d41b2153abd4ff6aed0d19ec96059b to your computer and use it in GitHub Desktop.
import React, { useState } from "react";
type Values = Record<string, boolean> | null;
interface Props {
items: {
label: string;
value: string;
}[];
onSubmit: (values: Values) => void;
initialValues: Values;
}
export const CheckboxForm: React.FC<Props> = ({
items,
onSubmit,
initialValues
}) => {
const [values, setValues] = useState<Values>(null);
const currentValues = values === null ? initialValues : values;
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { value, checked } = event.target;
setValues(prev => {
const prevValues = prev === null ? initialValues : prev;
return {
...prevValues,
[value]: checked
};
});
};
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
onSubmit(currentValues);
};
const isChecked = (value: string) => {
if (currentValues === null) {
return false;
}
return currentValues[value] || false;
};
return (
<form onSubmit={handleSubmit}>
<button onClick={() => setValues(initialValues)}>Reset</button>
{items.map(item => (
<label key={item.value}>
<input
type="checkbox"
value={item.value}
checked={isChecked(item.value)}
onChange={handleChange}
/>
<span>{item.label}</span>
</label>
))}
<button type="submit">submit</button>
</form>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment