Skip to content

Instantly share code, notes, and snippets.

@ark234
Last active February 7, 2018 16:45
Show Gist options
  • Save ark234/486bcc13e2c790b1ecaf35d7ca507b86 to your computer and use it in GitHub Desktop.
Save ark234/486bcc13e2c790b1ecaf35d7ca507b86 to your computer and use it in GitHub Desktop.
Example: how to use states in react
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = { bgColor: 'white' };
this.changeColorToRed = this.changeColorToRed.bind(this);
this.changeColorToGreen = this.changeColorToGreen.bind(this);
this.changeColorToBlue = this.changeColorToBlue.bind(this);
}
changeColorToRed(e) {
e.preventDefault();
this.setState({ bgColor: 'red' });
}
changeColorToGreen(e) {
e.preventDefault();
this.setState({ bgColor: 'green' });
}
changeColorToBlue(e) {
e.preventDefault();
this.setState({ bgColor: 'blue' });
}
render() {
return (
<div className="App" style={{ backgroundColor: this.state.bgColor }}>
<p>Background Color: {this.state.bgColor}</p>
<button onClick={this.changeColorToRed}>RED</button>
<button onClick={this.changeColorToGreen}>GREEN</button>
<button onClick={this.changeColorToBlue}>BLUE</button>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment