Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, {Component} from 'react';
- import ReactDOM from 'react-dom';
- import uuid from 'uuid';
- import './index.css';
- class App extends Component {
- heroes = [
- {
- name: "Batman",
- id: uuid(),
- },
- {
- name: "Wonder Woman",
- id: uuid(),
- },
- {
- name: "Titans",
- id: uuid(),
- },
- {
- name: "Supergirl",
- id: uuid(),
- },
- {
- name: "The Flash",
- id: uuid(),
- },
- ];
- state = {
- favComics: [],
- };
- toggleInFavComics = id => {
- let favComics;
- const isItemFavorite = this.state.favComics.find(
- favorite => favorite.id === id
- );
- if (isItemFavorite) {
- favComics = this.state.favComics.filter(
- favorite => favorite.id !== id
- );
- } else {
- favComics = [
- ...this.state.favComics,
- this.heroes.find(item => id === item.id),
- ]
- }
- this.setState({favComics});
- };
- render() {
- return (
- <div className="container">
- <ul className="comics">
- {this.heroes.map(({id, name}) => (
- <li
- key={id}
- className="comic"
- onClick={() => this.toggleInFavComics(id)}
- >
- {name}
- <span className="star">
- {this.state.favComics.find(
- favorite => favorite.id === id
- ) ? '★' : '☆'}
- </span>
- </li>
- ))}
- </ul>
- <div className="favorites">
- <p>Favorites:</p>
- {this.state.favComics.map(
- ({id, name}) => (
- <li className="favorite">{name}</li>
- )
- )}
- </div>
- </div>
- );
- }
- }
- ReactDOM.render(<App/>, document.getElementById('root'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement