using Material-ui checkboxes with the reactjs and redux

devanya picture devanya · Jun 15, 2017 · Viewed 20.9k times · Source

I want to display the selected checkbox items, for which I'm using material-ui checkbox.

Right now I'm only able to display the items with checkboxes, but I am not able to display the selected items.

I know it is easy but I'm new to reactjs and redux so finding it difficult to start.

Hoping for a help.

Thank you.

this.state = {
            data: [apple, kiwi, banana, lime, orange, grape],
        }}
    handleCheck(x) {
        this.state.checkedValues.push(x);
    }
render(){
       {this.state.data.map((x) =>
             <Checkbox
               label={x} key={x.toString()}
               onCheck={() => this.handleCheck(x)}
               checked=true
              }/>
          )}}

Answer

uneet7 picture uneet7 · Oct 25, 2018

Modifying the answer by @BravoZulu by adding the event as the argument in onChange() function.(Also note that use onChange() instead of onCheck() for material-UI checkboxes as shown in the official documentation). Also, don't forget to bind the function in the constructor. I hope this helps the community. Below is the code.

    class App extends Component {
    constructor(props) {
        this.handleCheck = this.handleCheck.bind(this);
        super(props);
        this.state = {
        data: [apple, kiwi, banana, lime, orange, grape],
        checkedValues: []
        }
    }
    handleCheck(e,x) {
        this.setState(state => ({
        checkedValues: state.checkedValues.includes(x)
            ? state.checkedValues.filter(c => c !== x)
            : [...state.checkedValues, x]
        }));
    }

    render() {
        return (<div>
        { this.state.data.map(x =>
            <Checkbox
            label={x} key={x.toString()}
            onChange={e => this.handleCheck(e,x)}
            checked={this.state.checkedValues.includes(x)}
            />
        )}}
        </div>)
    }
}