0
toggleCheckbox = (type) => {  
  if(this.state.active_class === type)  
  {  
    this.setState({active_class:'health'});  
  }   
  else
  {
    this.setState({ active_class: type });  
  }

}

This Button code called with above method

The Above Code only Works for Single Selection, How can i do it for multiple selection?

And I Used rails api to store slected categories

<Button value="1" className={this.state.active_class === 'health' ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('health')}} > Health2 </Button>           
<Button value="2" className={this.state.active_class ==='financial' ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('financial')}} > Financial </Button>
<Button value="3" className={this.state.active_class === 'career' ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('career')}} > Career </Button>
<Button value="4" className={this.state.active_class === 'people' ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('people')}} > People & Relationships </Button>
Chaitanya
  • 23
  • 7

1 Answers1

0

To do multi select you should keep selected button names (or) values in the state.

this.state = {
  activeButtons: []
}

toggleCheckbox = (type) => {
  const { activeButtons } = this.state;
  const newActiveBUttons = [...activeButtons];

  if(activeButtons.includes?(type)){
    newActiveBUttons = activeButtons.splice(activeButtons.indexOf(type), 1 );
  } else {
    newActiveBUttons.push(type);
  }
}

render () {
  const { activeButtons } = this.state;

  return (
    <Button value="1" className={(activeButtons.indexOf('health') > -1)  ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('health')}} > Health2 </Button>           
    <Button value="2" className={(activeButtons.indexOf('financial') > -1) ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('financial')}} > Financial </Button>
    <Button value="3" className={(activeButtons.indexOf( 'career') > -1) ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('career')}} > Career </Button>
    <Button value="4" className={(activeButtons.indexOf( 'people') > -1) ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('people')}} > People & Relationships </Button>
  )
}

In this way, you can do multi-select. You can keep button value into state instead of names.

Narasimha Reddy - Geeker
  • 3,510
  • 2
  • 18
  • 23
  • Thank you! But It's raising Syntax error as Undefined token at the line if(activeButtons.includes?(type)){ newActiveBUttons = activeButtons.splice(activeButtons.indexOf(type), 1 ); } else { newActiveBUttons.push(type); } – Chaitanya Jun 27 '18 at 03:59