In my React project, I'm trying to set different icons for each item based on their existence in an array which I get from local storage.
table.js
import React from 'react';
import isMovieInFavorites from './favorites';
class Table extends React.Component {
constructor(props){
super(props);
this.state = {
movies: [],
//other state vars
}
}
//some other codes
render(){
return (
<div className="table-container">
<table>
{this.state.movies.map((row) => (
<tr key={row.id}>
<td>{row.title}</td>
<td className="icon"><i className={(isMovieInFavorites(row.id) ? "fas" : "far") + " fa-star"}></i></td>
</tr>
))}
</table>
</div>
);
}
}
I'm trying to change classname between fas
and far
based on isMovieInFavorites(id)
from
favorites.js
function isMovieInFavorites(id){
let movieArray = localStorage.getItem('faveMovieList') ? JSON.parse(localStorage.getItem('faveMovieList')) : [];
movieArray.forEach((movie)=>{
if(movie.id === id)
return true;
});
return false;
}
I guess I'm doing fine with this part:
{(isMovieInFavorites(row.id) ? "fas" : "far") + " fa-star"}
Cause the condition works well if I check the results in console.log
(inside favorites.js
). Also if I do something like {(row.id == 10 ? "fas" : "far") + " fa-star"}
, it works fine. But calling the function and checking the result somehow doesn't work and always will apply class far
even the result is true
.
What am I missing here? Is it wrong to call a function in this situation?
export default isMovieInFavorites;