Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs adding active class to button

I have five buttons, dynamically created. My target is: when any button is clicked to add active class to it, and of course if any other has that active class to remove it. How can I achieve that?

<div>
    {buttons.map(function (name, index) {
        return <input type="button" value={name} onClick={someFunct} key={ name }/>;
   })}
</div>
like image 223
IntoTheDeep Avatar asked Aug 16 '16 16:08

IntoTheDeep


People also ask

How do you add an active class to a button with React?

To add or remove a class on click in React:Set the onClick prop on the element. Store the active state in a state variable. Conditionally add the class using the ternary operator.

How do I customize my React button?

You can customize the appearance of the Button by using the Cascading Style Sheets (CSS). Define the CSS according to your requirement, and assign the class name to the cssClass property.


2 Answers

You need to introduce state to your component and set it in onClick event handler. For example output of render method:

<div>
    {buttons.map(function (name, index) {
        return <input
                 type="button"
                 className={this.state.active === name ? 'active' : ''}
                 value={name}
                 onClick={() => this.someFunct(name)}
                 key={ name } />;
   })}
</div>

event handler (element method):

someFunct(name) {
    this.setState({ active: name })
}
like image 90
madox2 Avatar answered Sep 27 '22 19:09

madox2


One of the easiest way to add active class is setting state and changing that state on each switch, by the state value you can change the active class of the item.

I also had an same issue with switching the active class in list.

Example:

var Tags = React.createClass({
  getInitialState: function(){
    return {
      selected:''
    }
  },
  setFilter: function(filter) {
    this.setState({selected  : filter})
    this.props.onChangeFilter(filter);
  },
  isActive:function(value){
    return 'btn '+((value===this.state.selected) ?'active':'default');
  },
  render: function() {
    return <div className="tags">
      <button className={this.isActive('')} onClick={this.setFilter.bind(this, '')}>All</button>
      <button className={this.isActive('male')} onClick={this.setFilter.bind(this, 'male')}>male</button>
      <button className={this.isActive('female')} onClick={this.setFilter.bind(this, 'female')}>female</button>
      <button className={this.isActive('child')} onClick={this.setFilter.bind(this, 'child')}>child</button>
      <button className={this.isActive('blonde')} onClick={this.setFilter.bind(this, 'blonde')}>blonde</button>
     </div>
  }
});

hope this will help you!

like image 36
Arun Yokesh Avatar answered Sep 27 '22 20:09

Arun Yokesh