DEV Community

Checkbox Group Component in React-Final-Form

Victor R. on November 06, 2018

Posted November 6, 2018 Going to keep this short, because, by the time you most likely find this post, all you want is to just see it work, then...
Collapse
 
inimist profile image
Arvind Kumar • Edited

The first issue, fields.remove. Here is the updated toggle function:

const toggle = (event, option) => {
    if (event.target.checked) {
        fields.push(option);
    } else {
        const index = fields.value.indexOf(option)
        fields.remove( index );
    }
};
Enter fullscreen mode Exit fullscreen mode

The "default checked" issue. Here is the updated code:

<input type="checkbox" onChange={event => toggle(event, option.id)} checked={inArray(option.id, fields.value)} />
Enter fullscreen mode Exit fullscreen mode

And inArray function:

const inArray = (needle, haystack) => {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(typeof haystack[i] == 'object') {
            if(arrayCompare(haystack[i], needle)) return true;
        } else {
            if(haystack[i] == needle) return true;
        }
    }
    return false;
}
Enter fullscreen mode Exit fullscreen mode

And arrayCompare helper function:

function arrayCompare(a1, a2) {
    if (a1.length != a2.length) return false;
    var length = a2.length;
    for (var i = 0; i < length; i++) {
        if (a1[i] !== a2[i]) return false;
    }
    return true;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vladislavrus profile image
Владислав Курочкин

HI! Thank you for a nice article! Just noticed a little problem - according to the docs, fields.remove accepts an index of item, not an item itself, source: npmjs.com/package/react-final-form...

Collapse
 
jasonburnell98 profile image
jasonburnell98

Thank you so much. I was able to render the textfield just fine but was having trouble with checkboxes. This is exactly what I needed!

Collapse
 
mschipperheyn profile image
Marc Schipperheyn

The Material ui version is missing the checked attribute for the checkbox, so it won't process any existing values

Collapse
 
jasonnavarro86 profile image
Jason Navarro

@marc Were you able to find a solution to this problem? I am trying to set my checkboxes to default checked but it wont allow users to uncheck them.

Collapse
 
codeprada profile image
codeprada

Beautiful and concise. Exactly how I like my tutorials.

Collapse
 
jasonnavarro86 profile image
Jason Navarro

I am trying to set my checkboxes to default checked but it wont allow users to uncheck them. Do you know of a solution?