Formik: How to populate array with checkboxes?

Created on 21 Jan 2018  路  9Comments  路  Source: formium/formik

How to populate array with checkboxes?

Hi, I'm wondering if it's possible to do this.
I have 2 check-boxes, and every time one is checked, an array should be populated. I've been playing around, even tried the latest FieldArray, but I'm not sure I understand well how to use it, or even if it's for that purpose.

Info

I am using Formik component with render method.
Something like:

import React from 'react';
import { render } from 'react-dom';
import { Formik } from 'formik';


const App = () => (
  <div>
    <h1>My Form</h1>
    <Formik
      initialValues={{
        groups: [],
      }}
      onSubmit={values =>
        console.log(values)
        // Expected output would be something like:
        // {groups: ['admin', 'normal']}
      }
      render={props => (
        <form onSubmit={props.handleSubmit}>
          <input
            type="checkbox"
            name="groups.0"
            value="admin"
            onChange={props.handleChange}
            onBlur={props.handleBlur}
            checked={props.values.groups === 'admin'}
          />
          Admin
          <br/>
          <input
            type="checkbox"
            name="groups.1"
            value="normal"
            onChange={props.handleChange}
            onBlur={props.handleBlur}
            checked={props.values.groups === 'normal'}
          />
          Normal
          <br />

          <button type="submit" >
            Submit
          </button>
        </form>
      )}
    />
  </div>
);

render(<App />, document.getElementById('root'));

Here is an example: https://codesandbox.io/s/03pmmoo0kp

But what I really want is to have this as a result:

{
  groups: ['admin', 'normal']
}

Is it possible doing something like that? What am I missing?

Question stale

Most helpful comment

Example for a checkbox array using FieldArray: https://codesandbox.io/s/o5pw1vx916

All 9 comments

Okay, found a solution. I'm still wondering if it's the way to go:

import React from 'react';
import { render } from 'react-dom';
import { Formik } from 'formik';


const App = () => (
  <div>
    <h1>My Form</h1>
    <Formik
      initialValues={{
        groups: [],
      }}
      onSubmit={values => {
        values = { ...values, groups: values.groups.filter(e => e)}
        console.log(values)
        // Expected output would be something like:
        // {groups: ['admin', 'normal']}
      }}
      render={props => (
        <form onSubmit={props.handleSubmit}>
          <input
            type="checkbox"
            name="groups"
            onChange={(event) => {
              const value = event.target.checked ? 'admin' : null
              props.setFieldValue('groups.0', value)
            }}
            checked={props.values.groups.includes('admin')}
          />
          Admin
          <br/>
          <input
            type="checkbox"
            name="groups"
            onChange={(event) => {
              const value = event.target.checked ? 'normal' : null
              props.setFieldValue('groups.1', value)
            }}
            checked={props.values.groups.includes('normal')}
          />
          Normal
          <br />

          <button type="submit" >
            Submit
          </button>
        </form>
      )}
    />
  </div>
);

render(<App />, document.getElementById('root'));

I don't like the idea of having an array with null elements as a result, like [null, 'normal'], that's why the map in the onSubmit.

https://codesandbox.io/s/nwl7732l4l

Hey @Woile - I've dropped a demo of checkboxes and radio buttons over on another issue: https://github.com/jaredpalmer/formik/issues/363#issuecomment-359806276

Hopefully that helps with your use case

@adamduncan thanks!
Looks like a great solution, I would've expect it to be a bit more straightforward, but it looks good

Yeah, agreed 馃 Glad it's doable, but hopefully there's a simpler way to achieve it

@jaredpalmer - now v0.11 is released and FieldArray's stable, is it possible to add examples of creating fieldsets of multiple radio and checkbox inputs please? Seems such a common feature of forms, but yet to see a definitive example in the docs. Thanks!

@jaredpalmer Great library!

I'm also trying to build a multi checkbox input linked to an array in values. What is the best way to do this with FieldArray? I have it working as a custom component but FieldArray feels like it should be the built-in way to achieve it.

I'm having difficulty with FieldArray since it doesn't pass children as a prop here: https://github.com/jaredpalmer/formik/blob/b72cf00cb218336f62a181eaef7d04a3ed4becab/src/FieldArray.tsx#L233

Example for a checkbox array using FieldArray: https://codesandbox.io/s/o5pw1vx916

Hola! So here's the deal, between open source and my day job and life and what not, I have a lot to manage, so I use a GitHub bot to automate a few things here and there. This particular GitHub bot is going to mark this as stale because it has not had recent activity for a while. It will be closed if no further activity occurs in a few days. Do not take this personally--seriously--this is a completely automated action. If this is a mistake, just make a comment, DM me, send a carrier pidgeon, or a smoke signal.

ProBot automatically closed this due to inactivity. Holler if this is a mistake, and we'll re-open it.

Was this page helpful?
0 / 5 - 0 ratings