6 - Dynamic Movie List with Filtering and Sorting

Description

Create a React application that displays a dynamic list of movies. The application should allow users to filter movies by genre and sort movies by title or release year.

Algorithm

  1. Initialize a state variable to store the list of movies.

  2. Render a list of movies with filters and sort options.

  3. Define functions to filter movies by genre and sort movies by title or release year.

  4. Update the movie list based on user input.

Classes

MovieList: A React component that manages the movie list state and renders the movie list, filters, and sort options.

Code

import React, { useState } from 'react';

function MovieList() {
  const [movies, setMovies] = useState([
    { title: 'Movie 1', genre: 'Action', releaseYear: 2020 },
    { title: 'Movie 2', genre: 'Comedy', releaseYear: 2019 },
    { title: 'Movie 3', genre: 'Action', releaseYear: 2021 },
  ]);

  const [filterGenre, setFilterGenre] = useState('');
  const [sortOption, setSortOption] = useState('title');

  const handleFilterChange = (event) => {
    setFilterGenre(event.target.value);
  };

  const handleSortChange = (event) => {
    setSortOption(event.target.value);
  };

  const filteredMovies = movies.filter((movie) => {
    if (filterGenre) {
      return movie.genre === filterGenre;
    }
    return true;
  });

  const sortedMovies = filteredMovies.sort((a, b) => {
    if (sortOption === 'title') {
      return a.title.localeCompare(b.title);
    } else {
      return a.releaseYear - b.releaseYear;
    }
  });

  return (
    <div>
      <select value={filterGenre} onChange={handleFilterChange}>
        <option value="">All Genres</option>
        <option value="Action">Action</option>
        <option value="Comedy">Comedy</option>
      </select>
      <select value={sortOption} onChange={handleSortChange}>
        <option value="title">Sort by Title</option>
        <option value="releaseYear">Sort by Release Year</option>
      </select>
      <ul>
        {sortedMovies.map((movie) => (
          <li key={movie.title}>{movie.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default MovieList;

Explanation

The code defines a MovieList component that utilizes the useState hook to initialize state variables for the movie list, filter genre, and sort option. The component renders a list of movies, filters, and sort options. The handleFilterChange and handleSortChange functions update the filter genre and sort option state variables, respectively. The filteredMovies and sortedMovies variables are calculated based on the user input, and the sorted movie list is rendered.

Possible Future Enhancements

  • Add more filter options (e.g., release year, director).

  • Implement a search bar to search movies by title or description.

  • Display movie details (e.g., plot, cast) when a movie is selected.

  • Integrate with a movie database API to fetch movie data dynamically.

Last updated