I'm making Add to favorite function in React. Thanks to everyone's help I could somehow make that work except for toggling like and dislike. I coded like "likes: this.state.likes.filter(e => e.name !== person.name)" just because someone advised me to code so. To be honest I don't understand the code above maybe because it's ES6 syntax. How does it look like in ES5? And right now that code is not working, elements are not added to the array properly. How do I fix this code?
import React from 'react';
import axios from 'axios';
import IcoMoon from 'react-icomoon';
export default class PersonList extends React.Component {
state = {
persons: [],
likes: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
handleClick = person => {
if (this.state.likes.filter(e => e.name === person.name).length > 0) {
this.setState({
likes: this.state.likes.filter(e => e.name !== person.name)
});
console.log(this.state.likes);
return;
}
this.setState({
likes: [...this.state.likes, person]
});
};
likesTemplate = item => <li key={item}>{item}</li>;
renderLikes = () => {
return this.state.likes.map(i => this.likesTemplate(i));
}
render() {
return (
<div>
{this.state.persons.map(person => {
return <li key={person.name}><IcoMoon icon="heart" onClick={() => {this.handleClick(person.name)}} />{person.name}</li>}
)}
<h2>Favorite Person</h2>
<ul>
{this.renderLikes()}
</ul>
</div>
)
}
}