Sammy Sung
Sammy Sung

Reputation: 311

On click button colour change in React

I am currently having a little trouble with respect to getting a button colour to change on click:

My current code for button is as follows:

handleClick = () => {
   secondary=true
 }
<RaisedButton className={classPrefix + '-listToggle'}
  label="List View"
  onClick = {this.handleClick}
  icon={<Icon name="list" size={15} />}
/>

I also have a boolean called "secondary", which if 'true', changes the background color of the button. If I do the following code:

<RaisedButton className={classPrefix + '-listToggle'}
  label="List View"
  onClick = {this.handleClick}
  secondary=true
  icon={<Icon name="list" size={15} />}
/>

The button colour changes only on load, and remains the same if clicked.

What I ultimately want it to do is if button is clicked, set secondary to true, else, leave false.

Help?

Upvotes: 0

Views: 2380

Answers (1)

kind user
kind user

Reputation: 41913

I would suggest you to use state to determine if button is secondary or not. Anyways you didn't even init the secondary variable anywhere.

class App extends React.PureComponent {

  state = {
    active: false,
  };

  handleClick = () => {
    this.setState({ active: true });
  };

  render() {
    return (
      <RaisedButton className={classPrefix + '-listToggle'}
        label="List View"
        onClick={this.handleClick}
        icon={<Icon name="list" size={15} />}
      />

      <RaisedButton className={classPrefix + '-listToggle'}
        label="List View"
        secondary={this.state.active}
        icon={<Icon name="list" size={15} />}
      />
    )
  }
}

Upvotes: 3

Related Questions