Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. import React, {Component} from 'react';
  2. import ReactDOM from 'react-dom';
  3. import uuid from 'uuid';
  4. import './index.css';
  5.  
  6. class App extends Component {
  7. heroes = [
  8. {
  9. name: "Batman",
  10. id: uuid(),
  11. },
  12. {
  13. name: "Wonder Woman",
  14. id: uuid(),
  15. },
  16. {
  17. name: "Titans",
  18. id: uuid(),
  19. },
  20. {
  21. name: "Supergirl",
  22. id: uuid(),
  23. },
  24. {
  25. name: "The Flash",
  26. id: uuid(),
  27. },
  28. ];
  29. state = {
  30. favComics: [],
  31. };
  32.  
  33. toggleInFavComics = id => {
  34. let favComics;
  35. const isItemFavorite = this.state.favComics.find(
  36. favorite => favorite.id === id
  37. );
  38. if (isItemFavorite) {
  39. favComics = this.state.favComics.filter(
  40. favorite => favorite.id !== id
  41. );
  42. } else {
  43. favComics = [
  44. ...this.state.favComics,
  45. this.heroes.find(item => id === item.id),
  46. ]
  47. }
  48. this.setState({favComics});
  49. };
  50. render() {
  51. return (
  52. <div className="container">
  53. <ul className="comics">
  54. {this.heroes.map(({id, name}) => (
  55. <li
  56. key={id}
  57. className="comic"
  58. onClick={() => this.toggleInFavComics(id)}
  59. >
  60. {name}
  61. <span className="star">
  62. {this.state.favComics.find(
  63. favorite => favorite.id === id
  64. ) ? '★' : '☆'}
  65. </span>
  66. </li>
  67. ))}
  68. </ul>
  69. <div className="favorites">
  70. <p>Favorites:</p>
  71. {this.state.favComics.map(
  72. ({id, name}) => (
  73. <li className="favorite">{name}</li>
  74. )
  75. )}
  76. </div>
  77. </div>
  78. );
  79. }
  80. }
  81.  
  82. ReactDOM.render(<App/>, document.getElementById('root'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement