Skip to content

Instantly share code, notes, and snippets.

@luandevpro
Last active July 14, 2019 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luandevpro/b8c6bd2532bff681db4f5b23bc7ddf4d to your computer and use it in GitHub Desktop.
Save luandevpro/b8c6bd2532bff681db4f5b23bc7ddf4d to your computer and use it in GitHub Desktop.
import React from 'react';
import { Formik, Form, Field, FieldArray } from 'formik';
import styled from 'styled-components';
const languageState = ['vi', 'en', 'jp'];
export default () => {
const handleSubmit = values => {
console.log(values.languages);
};
return (
<Formik
onSubmit={handleSubmit}
initialValues={{
languages: [],
}}
>
{() => (
<Form>
<FieldArray name="languages">
{arrayHelpers => {
return languageState.map((language, index) => {
return (
<StyledWrap
key={index}
htmlFor={`languages.${index}.language`}
style={{ marginBottom: '10px' }}
>
<label htmlFor={`languages.${index}.language`}>
<input
id={`languages.${index}.language`}
type="checkbox"
name={`languages.${index}.language`}
value={language}
checked={arrayHelpers.form.values.languages.includes(language)}
onChange={e => {
if (e.target.checked) arrayHelpers.push(language);
else {
const idx = arrayHelpers.form.values.languages.indexOf(language);
arrayHelpers.remove(idx);
}
}}
hidden
className="check-custom"
/>
<span className="check-toggle" />
<label style={{ marginLeft: '10px' }} htmlFor={`languages.${index}.language`}>
{language}
</label>
</label>
</StyledWrap>
);
});
}}
</FieldArray>
<br />
<button type="submit">submit</button>
</Form>
)}
</Formik>
);
};
const StyledWrap = styled.div``;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment