Guest User

Untitled

a guest
Jan 24th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. import React, { Component } from 'react';
  2. import PubSub from 'pubsub-js';
  3.  
  4. class App extends Component {
  5. state = { show: true };
  6. render() {
  7. return (
  8. <div className="App">
  9. <button onClick={() => this.setState(state => ({ show: !state.show }))}>
  10. {this.state.show ? 'Hide panel' : 'Show panel'}
  11. </button>
  12. <Toggler />
  13. {this.state.show && <Panel initialColor="blue" />}
  14. </div>
  15. );
  16. }
  17. }
  18.  
  19. class Toggler extends Component {
  20. render() {
  21. return (
  22. <div>
  23. <button type="button" onClick={() => PubSub.publish('TOGGLE')}>
  24. Toggle red/blue
  25. </button>
  26. <button type="button" onClick={() => PubSub.publish('SET PINK')}>
  27. Set pink
  28. </button>
  29. <button type="button" onClick={() => PubSub.publish('SET YELLOW')}>
  30. Set yellow
  31. </button>
  32. </div>
  33. );
  34. }
  35. }
  36.  
  37. class Panel extends Component {
  38. state = {
  39. color: this.props.initialColor
  40. };
  41.  
  42. subscriptions = [
  43. PubSub.subscribe('SET YELLOW', () => this.setState({ color: 'yellow' })),
  44. PubSub.subscribe('SET PINK', () => this.setState({ color: 'pink' })),
  45. PubSub.subscribe('TOGGLE', () => {
  46. console.log(`Toggling from ${this.state.color}.`);
  47. this.setState(({ color }) => ({
  48. color: color === 'red' ? this.props.initialColor : 'red'
  49. }));
  50. })
  51. ];
  52.  
  53. componentWillUnmount = () => this.subscriptions.forEach(PubSub.unsubscribe);
  54.  
  55. render() {
  56. return (
  57. <div
  58. style={{ width: 100, height: 100, backgroundColor: this.state.color }}
  59. />
  60. );
  61. }
  62. }
  63.  
  64. export default App;
Add Comment
Please, Sign In to add comment