Introduction

Are you a React developer looking to hone your skills or a beginner eager to create something cool? Building a movie app using React.js is a fun and rewarding project that allows you to explore the power of React components, state management, and API integration. In this tutorial, we’ll walk through building a simple movie app that fetches and displays movie data using a public API.

Prerequisites

Before we begin, make sure you have the following installed on your system:

  • Node.js and npm (Node Package Manager)
  • A code editor (e.g., Visual Studio Code)
  • Basic knowledge of JavaScript, React, and APIs

Project Overview

Our movie app will:

  1. Display a list of movies fetched from an external API.
  2. Allow users to search for specific movies by title.
  3. Show detailed information about a selected movie.

We’ll use the OMDb API, a free API for movie data. You’ll need an API key to access this service. Register on their website and obtain your API key.

Step 1: Setting Up the React Project

First, create a new React application using Create React App. Open your terminal and run:

				
					npx create-react-app movie-app
				
			

Navigate into your project directory:

				
					cd movie-app
				
			

Step 2: Cleaning Up the Default Template

Before we start coding, clean up the default files created by Create React App. Remove the following files inside the src folder:

  • App.css
  • App.test.js
  • logo.svg
  • reportWebVitals.js
  • setupTests.js

Modify index.css to set some basic styling:

 
				
					body {
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}
				
			

Update App.js to have a minimal structure:

				
					import React from 'react';

function App() {
    return (
        <div className="App">
            <h1>Movie App</h1>
        </div>
    );
}

export default App;
				
			

Step 3: Creating Components

We’ll create separate components to make our code more organized:

  1. SearchBar: For inputting the search query.
  2. MovieList: To display a list of movies.
  3. MovieCard: To display details of each movie.

Create a new directory called components inside the src folder, and then create three new files: SearchBar.js, MovieList.js, and MovieCard.js.

Creating the SearchBar Component

Let’s create a simple search bar component to take user input. Open SearchBar.js and add the following code:

 
				
					import React from 'react';

const SearchBar = ({ searchQuery, setSearchQuery }) => {
    return (
        <div className="search-bar">
            <input 
                type="text" 
                placeholder="Search for movies..." 
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
            />
        </div>
    );
};

export default SearchBar;
				
			

Creating the MovieCard Component

The MovieCard component will display individual movie details such as title, year, and a poster image. Open MovieCard.js and add the following code:

				
					import React from 'react';

const MovieCard = ({ movie }) => {
    return (
        <div className="movie-card">
            <img src={movie.Poster} alt={movie.Title} />
            <div className="movie-info">
                <h3>{movie.Title}</h3>
                <p>{movie.Year}</p>
            </div>
        </div>
    );
};

export default MovieCard;
				
			

Creating the MovieList Component

The MovieList component will render a list of MovieCard components. Open MovieList.js and add the following code:

				
					import React from 'react';
import MovieCard from './MovieCard';

const MovieList = ({ movies }) => {
    return (
        <div className="movie-list">
            {movies.map((movie) => (
                <MovieCard key={movie.imdbID} movie={movie} />
            ))}
        </div>
    );
};

export default MovieList;
				
			

Step 4: Integrating the API

Now, let’s fetch movie data using the OMDb API. We’ll make an API call based on the user’s search input.

Fetching Data in the App Component

Open App.js and modify it to include state management and API integration:

				
					import React, { useState, useEffect } from 'react';
import SearchBar from './components/SearchBar';
import MovieList from './components/MovieList';

function App() {
    const [movies, setMovies] = useState([]);
    const [searchQuery, setSearchQuery] = useState('Batman');

    useEffect(() => {
        const fetchMovies = async () => {
            const response = await fetch(`https://www.omdbapi.com/?s=${searchQuery}&apikey=YOUR_API_KEY`);
            const data = await response.json();
            if (data.Search) {
                setMovies(data.Search);
            }
        };

        fetchMovies();
    }, [searchQuery]);

    return (
        <div className="App">
            <h1>Movie App</h1>
            <SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} />
            <MovieList movies={movies} />
        </div>
    );
}

export default App;
				
			

Replace YOUR_API_KEY with your actual OMDb API key. This code will fetch the movie data every time the searchQuery state changes.

Step 5: Styling the App

To make our app look more appealing, let’s add some CSS. Open the index.css file and add the following styles:

				
					.App {
    text-align: center;
    padding: 20px;
}

.search-bar {
    margin-bottom: 20px;
}

.search-bar input {
    width: 60%;
    padding: 10px;
    font-size: 16px;
    border-radius: 4px;
    border: 1px solid #ccc;
}

.movie-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 20px;
}

.movie-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    width: 200px;
    overflow: hidden;
}

.movie-card img {
    width: 100%;
    height: auto;
}

.movie-info {
    padding: 10px;
}
				
			

Step 6: Testing the Application

Now that everything is set up, run your application by executing the following command in your terminal:

				
					npm start
				
			

Your movie app should now be running on http://localhost:3000. Try searching for different movie titles to see the app in action!

Step 7: Additional Features and Enhancements

Our movie app is functional, but there’s always room for improvement! Here are some ideas for enhancements:

  1. Movie Details Page: Implement routing to navigate to a detailed page for each movie showing more information like the plot, director, actors, etc.
  2. Loading Spinner: Add a loading spinner while fetching data from the API to improve user experience.
  3. Error Handling: Show an error message if no movies are found or if the API request fails.
  4. Pagination: If the search results have more than 10 movies, implement pagination to navigate through the results.
  5. Mobile Responsiveness: Make sure the app is fully responsive and works well on all screen sizes.

Conclusion

Congratulations! You’ve successfully built a movie app using React.js, complete with API integration and dynamic searching capabilities. This project is a great way to practice React components, hooks, and working with APIs. As you continue to improve and add features, you’ll gain more confidence in your React development skills.

Happy coding! 🎬🍿