Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Material-ui checkboxes with the reactjs and redux

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
              }/>
          )}}
like image 328
devanya Avatar asked Jun 15 '17 18:06

devanya


1 Answers

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>)
    }
}
like image 87
uneet7 Avatar answered Sep 26 '22 16:09

uneet7