I am following training videos to learn ReactJS so this code is from there and I have these snippets
export default function MoviesGrid() {
const [genre, setGenre]= useState(["All"]);
const handleGenreFilterChange = (e) => {
setGenre(e.target.value.toString());
}
const filterGenres = (movie, genre) => {
return genre.toString() === "All"
|| movie.genre.toLowerCase() === genre.toString().toLowerCase();
}
return ( ...
<div className = "filter-slot">
<label>Genre</label>
<select value={genre} onChange={handleGenreFilterChange}
className="filter-dropdown">
<option>All</option>
<option>Horror</option>
<option>Action</option>
<option>Fantasy</option>
<option>Drama</option>
</select>
</div>
...
The training video didn’t have to include toString() in the filter method, but mine throws an error on the toLowerCase() and the genre === "All" doesn’t match if I don’t include them?
My react versions
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
I am running my application on firefox.
>Solution :
The issue with your code is related to how you’re handling the "All" genre filter.
-
toString(): In React, the value attribute of a select element is
usually a string. However, your genre state might be an array of
strings (["All"]). Calling .toString() on the state variable ensures
it’s converted to a string for comparison with the select element’s
value. -
toLowerCase(): When comparing strings for genre filtering, it’s good
practice to convert both values to lowercase. This ensures
case-insensitive filtering (e.g., "Horror" matches "horror"). -
"All" Genre Filter: Here’s the key point. You want to display all
movies when "All" is selected. However, the original logic
(genre.toString() === "All") wouldn’t work for two reasons:· If genre is an array, .toString() would return something like "All",
but with commas (e.g., "All").· Even if it were a single string, it
might not match exactly due to case sensitivity.
Here’s how you can fix the filtering logic:
const filterGenres = (movie, genre) => {
genre = genre.toLowerCase();
return genre === "all" || movie.genre.toLowerCase() === genre;
}