Anita
Anita

Reputation: 153

Reactjs onClick: how to set state of clicked buttons in a list

I have a list of buttons and I'm trying to figure out how to get state of each button that was selected like so (so at any one time I know which button(s) has/have been clicked):

// this.state.selectedTransport:
{ car: true,  train: false, plane: true } or
{ car: false, train: false, plane: true } or
{ car: true,  train: true,  plane: true } etc

see code here: http://jsbin.com/gizamovaco/1/edit?html,js,console,output

Upvotes: 1

Views: 1487

Answers (2)

slugo
slugo

Reputation: 1039

The main idea is to have the handleClick function in a parent component, and then you call it in your child component to update your parent's state and then pass it as props to your different children. I followed your existing structure and it resulted in something like this: JSbin.

Upvotes: 2

Tom Goldenberg
Tom Goldenberg

Reputation: 566

Something like this would work:

//Child
var SingleButton = React.createClass({
  render: function() {
    let { selectedTransport, type, text, handleClick } = this.props;
    let selected = selectedTransport[type];
    var style = selected ? { "backgroundColor":"yellow" } : {
      "backgroundColor":""
    };
    return (
      <button style={style} onClick={handleClick} name={type}> 
        {text}
      </button>
    )
  }
});

//Parent
var Categories = React.createClass({
  getInitialState: function() {
    return { 
      selectedTransport: {
        car: false,
        train: false,
        plane: false
      }
    }
  },
  handleClick: function(event) {
    console.log('CLICK');
    let { selectedTransport } = this.state;
    selectedTransport[event.target.name] = true;
    this.setState({ selectedTransport });
    console.log('TRANSPORT', this.state.selectedTransport);
  },

  render: function() {
    console.log('RENDERING', this.state);
    var transportType = ['car', 'train', 'plane'];
    return (
      <div>
        {transportType.map((type, idx) => (
          <SingleButton 
            {...this.state}
            text={type} 
            handleClick={this.handleClick} 
            key={idx} 
            type={type} 
          />
        ))
      </div>
    );
  }
});


ReactDOM.render(<Categories />, document.getElementById('app'));

Upvotes: 0

Related Questions