Skip to content

Instantly share code, notes, and snippets.

@rajatk16
Created March 14, 2019 05:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajatk16/c71258ab884810a6b7035a66e6aa5292 to your computer and use it in GitHub Desktop.
Save rajatk16/c71258ab884810a6b7035a66e6aa5292 to your computer and use it in GitHub Desktop.
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'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment