Created
October 21, 2019 02:39
-
-
Save maladr0it/38d41b2153abd4ff6aed0d19ec96059b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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