TheUnreal
TheUnreal

Reputation: 24462

React - change button color after clicking

I have the following button:

{this.steps.map((step, index) => (
    <Button variant="raised" color={(step.answer === 'done' ? 'primary' : 'default')}
                            onClick={this.markAs('done', step)}>
                                Done
                            </Button>
)}

my markAs() function looks like this:

markAs(value, step) {
        step.answer = value;
    }

Although step.answer changes to done, the color of the button stays the same.

class App extends Component {
   steps = [...some steps];
}

What's wrong?

Upvotes: 3

Views: 5915

Answers (2)

fyasir
fyasir

Reputation: 2970

A React re-render can only be triggered if a component’s state has changed. The state can change from a props change, or from a direct setState change. The component gets the updated state and React decides if it should re-render the component.

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props){
   super(props);
   this.state = {
     step: { answer: '' },
   };
   this.markAs = this.markAs.bind(this);
  }

  markAs() {
   this.setState({ step: { answer: 'done' } });
  }

  render(){
   return (
     <Button
       variant="raised"
       color={(this.state.step.answer === 'done' ? 'primary' : 'default')}
       onClick={this.markAs}
      > Done
      </Button>
   );
  }
}

Upvotes: 1

oklas
oklas

Reputation: 8220

You need to use react component state. Initialize the defult value for correspondent button. And change state after it is done.

constructor(props) {
  super(props)
  this.state = {
  }
  steps.forEach( (item,i) => {
    this.state[i] = 'not done'
  })
}

renderStep(step,stepId) {
  return (
    <Button
      variant="raised"
      color={this.state[stepId] === 'done' ? 'primary' : 'default')}
      onClick={this.setState({[stepId]:'done'}
    >
      Done
    </Button>
  )
}

in render you need to call like this (where stepId is position in step array)

<div>
  {renderStep(step,stepId)}
</div>

Upvotes: 0

Related Questions