Button doesn't change colors!

Hello, I’ve got the code right.
But the colors aren’t changed by the button.

import React from 'react';
import ReactDOM from 'react-dom';

const green = '#39D1B4';
const yellow = '#FFD712';

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: green };
  }
  
  changeColor() {
      	const newColor = this.state.color == green ? yellow : green;
    this.setState({color: newColor});  
    this.changeColor = this.changeColor.bind(this);
  }
  
  render() {
    return (
      <div style={{background: this.state.color}}>
        <h1>
          Change my color
        </h1>
        <button onClick={this.changeColor}>
          Change color
        </button>
      </div>
    );
  }
}

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

why do you do the binding of changeColor method within the changeColor method?

Yeah, thanks I solved it. But what’s the difference? :grinning:

bind() makes the method accessible by this, so that needs to be in the constructor, so the binding occurs

1 Like

Thanks man, appreciate the help! :smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.