Button doesn't change colors!


#1

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'));

#2

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


#3

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


#4

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


#5

Thanks man, appreciate the help! :smile:


#6

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