0

Code below is to get selected values(Like a search refinement/search ). For Example, If I click on the Political Checkbox, I should get Political Value If I click on the MovieCheckbox, I should get MovieValue as well as Political Value If I uncheck It should display only selected checkbox value. Below is the code which I have written

class Refinments extends Component {
    render(){
    const { handleChange,handleClick } = this.props;
    return(
    <Form>
       {['checkbox'].map(type => (
            <div key={`Political`} className="mb-1">
              <Form.Check 
                type={type}
                custom 
                id={`Political}`}
                label={`Political`}
                value={`Political`}
                onChange={handleChange.bind(this, "Political")}
              />
            </div>
        ))}
        {['checkbox'].map(type => (
            <div key={`movies`} className="mb-1">
              <Form.Check 
            type={type} custom
            id={`movies}`}
            label={`Movies`}
            value={`Movies`}
             onChange={handleChange.bind(this, "Movies")}
              />
            </div>
        ))}
     </Form>
     )}

export default Refinments;
3
  • Can you be more specific about your requirement and ['checkbox'].map is pointless as there will be only one iteration and its value is going to be 'checkbox'. Commented Feb 15, 2019 at 11:38
  • @Dan Philip: From this URL, I have taken checkbox component react-bootstrap.github.io/components/forms/… My requirement is refinements-filters Commented Feb 15, 2019 at 11:45
  • Can you share the code for this component class. Commented Feb 15, 2019 at 12:02

1 Answer 1

1

The best option is to store the selected values in a state variable. handleChange method checks if the changed checkbox value is in the valArr, If it is present it removes the value from the array and replaces the state variable with the new array and if its not present it simply pushes the value into the array.

So this.state.valArr will always and only have the selected checkbox values.

constructor(props) {
  super(props);
  this.state = {
    valArr: []
  }
}
handleChange = (val) => {
  let { valArr } = this.state;
  let index = valArr.indexOf(val);
  if (index != -1)
      valArr.splice(index, 1);
  else
      valArr.push(val);
  this.setState({ valArr });
}
render() {
  .
  .
  .
  <div key={`movies`} className="mb-1">
      <Form.Check 
        type={type} custom
        id={`movies}`}
        label={`Movies`}
        value={`Movies`}
        onChange={this.handleChange}
      />
  </div>
}
Sign up to request clarification or add additional context in comments.

Comments

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.