React

by pleinx

HTML

<div id="app"></div>

CSS

body {
  padding: 50px;
}

button {
  margin-right: 20px;
}

React

class ListenerApp extends React.Component {
	constructor() {
  	super();
    
    this.state = {
    	action: null
    };
  }

  render() {
  	const {color} = this.state;
    const style = {background: color};
  
    return (
     	<div>
     	  <ExampleApp onColorChange={(color) => this.handleColorChange(color)}/>
        {this.state.action}
     	</div>
    );
  }
  
  handleColorChange(color) {
  		const action = color === 'red' ? 'fire' : 'water';
  		this.setState({action: action});
  }
}

class ExampleApp extends React.Component {
  constructor(props) {
    super(props);
    
    this.handleClick = this.handleClick.bind(this);
    
    this.state = {
    	color: null
    };
  }
  
  render() {
  	const {color} = this.state;
    const style = {background: color};
  
    return (
     	<button style={style} onClick={this.handleClick}>
     	    Click Me
     	</button>
    );
  }
  
  handleClick(e) {
  	const {onColorChange} = this.props;
  	const newColor = this.state.color === 'red' ? 'blue' : 'red';
  
    this.setState({color: newColor});
    onColorChange && onColorChange(newColor);
  }
}

ReactDOM.render(<ListenerApp/>, document.querySelector("#app"))