3

How to get multiple checkboxes value ? Ref not working in material ui checkbox, no idea why.

<Checkbox key={i} label={catagory.name} ref="categories" value={catagory_name} name="category"  />

for example : example

Without material-ui you can get the value by ref, but with material-ui it require another method to get checkbox value.

I get the data from API, so it will add more from time to time. How to get the value? What function I should write? Anyone know ?

3
  • 1
    Possible duplicate of Multiple checkbox values handling with ReactJS Commented Jul 4, 2017 at 18:38
  • that one ain't material ui checkbox Commented Jul 4, 2017 at 22:54
  • My apologies. However, it does carefully say "possible" duplicate. Best of luck with your code! Commented Jul 5, 2017 at 1:12

1 Answer 1

5

You can use build-in Material UI checkbox function - onChange. It will return the specified category and it's value.

app.js

class App extends Component {

  result = new Set();

  handleCheckbox(event, isChecked, value) {
    console.log(isChecked, value); 
    this.res.add(value);
    if (this.res.size === 3) console.log(this.res);
  }

  labelList = [{id: 1, category: 'a'}, {id: 2, category: 'b'}, {id: 3, category: 'c'}]; // your data

  render() {
    return (
      <div className="App">
        {this.labelList.map(element => (
          <CheckboxField
            key={element.id}
            label={element.category}
            category={element.category}
            onChange={this.handleCheckbox}
          />
        ))}
      </div>
    )
  }
}

Checkbox.js

export class CheckboxField extends React.PureComponent {

  handleCheck = (event, isInputChecked) => {
    this.props.onChange(event, isInputChecked, this.props.category);
  };

  render() {
    return (
          <Checkbox
            label={this.props.category}
            iconStyle={{fill: '#000'}}
            value={this.props.category}
            onCheck={this.handleCheck}
          />
    )}
}
Sign up to request clarification or add additional context in comments.

6 Comments

How to make it array ? eg:[a, b, c]
@Alan Still having problems?
@Alan Get array? You want to get array after checking all checkboxes? Array of what?
i want all 3 values in an array after checked and post to database. So I need array of the values of checkbox been checked. Can get what I mean ?
@Alan After checking all checkboxes, yeah?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.