Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use React and forms to get an array of checked checkbox values?

I am trying to build a filter for my portfolio website. Checkboxes that let you pick a technology (react, redux, jquery etc.) to display a piece of work(s) that contain(s) that/those technologies. So every time the user clicks on a box, I want to add the value (JavaScript, Redux, React etc.) to an array that I use in another function to check against my portfolio pieces and filter out what isn't there.

I am finding this very difficult and I think it should be quite simple. Can someone point me in the right direction? Is there a way to simply have a function trigger (onChange callback?) that reads the checked/unchecked status of my form input elements and then updates my state array accordingly? Can I get the status of all the checkboxes simply in React? Do I need to have individual state of checked/unchecked for my checkboxes?

It seems that jQuery makes it pretty possible with selectors with:

$('input[type="checkbox"]:checked').each(function () {}
like image 946
MindfulBell Avatar asked May 10 '16 04:05

MindfulBell


People also ask

How do you handle a checkbox in React form?

Controlling the input checkbox As mentioned earlier, React recommends making our form elements a controlled field. To do this, we must add a component state to manage the user's input and then pass the state variable to the input. For checkbox input, we will assign the state to the input checked attribute.

How do I see all checkboxes in Reactjs?

list. map(item => <div> <input key={item.id} type="checkbox" name={item.name} value={item.name} checked={item. isChecked} onChange={this. handleChange} /> <label>{item.name}</label> </div> ) } render(){ return( <div> <input type="checkbox" value="checkAll" checked={this.


1 Answers

Here's how I'm doing it:

// util.js
import getPath from 'lodash/get';
import setIn from 'lodash/fp/set';

export function linkMultiCheck(name, value) {
    return {
        checked: getPath(this.state, name, []).includes(value),
        onChange: ev => {
            let values = getPath(this.state, name, []);
            if(ev.target.checked) {
                values = [...values, value];
            } else {
                values = values.filter(v => v !== value);
            }
            this.setState(setIn(name, values));
        },
    }
}

// form.js
<ul>
    {options.branches.map(branch => (
        <li key={branch.id} className="checkbox">
            <label>
                <input type="checkbox" name={this.id} {...this::linkMultiCheck('formData.branchIds',branch.id)}/>
                {branch.id}
            </label>
        </li>
    ))}
</ul>

i.e., if a checkbox is checked, append it to the current array of values. If it's unchecked, filter it out.

I'm using lodash here so that we can set deeply nested state values using dot notation.

like image 174
mpen Avatar answered Oct 03 '22 00:10

mpen