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

后端 未结 2 1119
庸人自扰
庸人自扰 2021-02-06 06:08

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/

2条回答
  •  不知归路
    2021-02-06 06:46

    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
    
      {options.branches.map(branch => (
    • ))}

    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.

提交回复
热议问题