Creating a dropdown menu feature that allows users to access movies with identical titles, utilizing React, Axios, and the MovieDB API

My latest project involves creating a movie search app where users can search for a movie and see details like the backdrop, poster image, title, and popularity displayed on the screen. However, I encountered an issue with accessing different movies with the same name. When searching for a movie like "Joker", only the first title that appears is accessed in my code.

const title = res.data['results'][0]['title'];

The [0] index indicates that it's grabbing the first movie from the search results. Here's a visual representation of how the API search looks in the browser: https://i.sstatic.net/ij2nh.png

Depending on the search query, there may be multiple movie titles with the same name, each listed with a different number under the API (e.g., [0], [1], etc.). I believe I need to use a for loop or forEach method to iterate through results[number] and retrieve all the ['original_title'] or ['title'], displaying them as a drop-down menu during the search process instead of waiting until submission. This is my first React project, so I'm uncertain whether this logic should be implemented within the clickHandler or elsewhere.

While most of my code resides in Movielist.js, I've included all three of my code files here just in case. I'm open to alternative solutions that make it easier to search for movies with identical titles.

Movielist.js

import React from 'react';
import axios from 'axios';
import '../CSS/style.css'

export default class Movielist extends React.Component {
  state = {
    title: "",
    popularity: "",
    poster: "",
    background: "",
  }

    clickHandler = (event) => {
        if (event.keyCode === 13) {
           const query = event.target.value;
           const API_KEY = 'caf02a958f137f43327649b2b8721302';
    axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
      .then(res => {

        const title = res.data['results'][0]['title'];
        this.setState({ title });

        const popularity = res.data['results'][0]['popularity']
        this.setState({ popularity });

        const poster = res.data['results'][0]['poster_path']
        this.setState({ poster });

        const background = res.data['results'][0]['backdrop_path']
        this.setState({ background })


      })
        }
    }

  render() {
    const backgroundStyle = {
      backgroundImage: `linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), 
  url(https://image.tmdb.org/t/p/w500${this.state.background})`,

      backgroundSize: "cover",
      height: "100vh"
  }

    return (
      <div id="main-div" style={backgroundStyle}>
        <div id="second-div">
         <input type="search" id="search" onKeyDown={event => this.clickHandler(event)} />
         <h1 id="title">Title: {this.state.title}</h1>
         <h1 id="popularity">Popularity: {this.state.popularity}</h1>
         <img id="poster" src={`https://image.tmdb.org/t/p/w300${this.state.poster}`} />
      </div>
    </div>

    )
  }
}

App.js

import React from "react"
import Movielist from './components/Movielist'



function App() {
    return (
        <div>
            <Movielist />
        </div>

    )
}

export default App

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

Answer №1

There are numerous possibilities and options to consider when approaching this issue. One approach is:

Within the clickHandler function, update the entire results array in the state:

this.setState({ results: res.data.results })

Then, within the render method, utilize the .map function to loop through the results and render something for each item:

<div id="main-div" style={backgroundStyle}>
<input type="search" id="search" onKeyDown={event => this.clickHandler(event)} />
  <div id="results">
    {this.state.results.map(item => {
      return (
        <div key={item.id}>
           <h1 id="title">Title: {item.title}</h1>
           <h1 id="popularity">Popularity: {item.popularity}</h1>
           Essentially customize the rendering
        </div>
      )
    })}
  <div>
</div>

To limit the number of items displayed, you can use the .slice function such as

this.state.results.slice(0, 5).map(...
(which will only show the first 5 items). This functionality can be implemented within the render method or within setState

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Content that refuses to stretch

Lately, I've been working on making sure my footer stays at the bottom of the page while allowing the middle content to stretch so that the footer placement will be correct regardless of the resolution the website is viewed in. It has been a bit sinc ...

Mapping prop passed to client component in NEXT 13: A step-by-step guide

Hello, I'm currently navigating through the Next 13 APP directory and have encountered a scenario where everything functions smoothly when I integrate the server component as shown below: const Tasks = async () => { const { tasks } = await getAll ...

Issues with Twitter Bootstrap Rendering in Internet Explorer

Encountering significant challenges in making a Twitter Bootstrap site compatible with Internet Explorer. Visit for the site in question. Below are screenshots from Chrome and Internet Explorer along with the corresponding HTML code. The issue is with the ...

relocate the image with an identical filename stored in the variable

Having trouble moving an image to a new position when clicking on its small thumbnail. I've attempted using jquery's find() function but it doesn't seem to be working... $('#slide1_controls img').click(function (event){ var sr ...

Issue with Bootstrap 4's vertical alignment center in flex layout not functioning as expected

Im using Bootstrap 4 to create a responsive layout with 3 columns that adjust order, width, and horizontal alignment based on screen size. Everything is functioning correctly except for the horizontal center alignment of the images on screens smaller than ...

Transform the information sent from the server into a user-friendly interface using typescript on the frontend

Received data from the backend looks like this: id: number; user_id: number; car_brand: string; car_model: string; vin: string; equipment: string; reg_number: string; car_mileage: number; car_year: string; Meanwhile, the interface in the ...

The act of splicing an array in React causes continuous rerendering

Within the update(changeProps) function, my code resembles the following: update(changedProps) { if (this.person) { this.__arr = ['hi', 'hi', 'hi']; } else { this.__arr = ['bye', &apos ...

Combine several divs into a block of individual divs

As part of my project, I am working on creating a number board where specific numbers need to merge into a single cell. Please see the picture for reference https://i.sstatic.net/99WJq.png Below is the HTML code snippet that I have tried. I used margin fo ...

Adjust the dimensions of all images using JavaScript

Is there a way to resize images using javascript? I attempted the following: var images = document.getElementByTagName('img') images.max_width = '100px' images.max_height = '100px' Unfortunately, it did not have the desired e ...

The `useState` variable seems to always be playing catch-up with its value

Apologies if my question seems vague, I am still learning JS and react. My issue is that in the code below, the newFilter state hook lags one step behind event.target.value. This value should have been assigned to newFilter on onChange, so why does newFilt ...

Floating division element above responsive divisions

element, I am in the process of developing a straightforward online card interface. In this interface, there will be a user profile picture displayed above some details about that user. However, to achieve this layout, the profile picture must appear hove ...

What is the best way to transform a string into React components that can be displayed on the screen?

Stored in my database are strings that contain partial HTML content, as shown below: “Intro<br /><br />Paragraph 1<br /><br />Paragraph 2” If I want to display this string within a new <p> element, what is a straightforwa ...

I'm having trouble figuring out how to perfectly center this div on all types of devices

As someone who is new to css, I have been struggling to center these divs in the middle of the page across all devices despite searching extensively online and trying various solutions without any success. Check out my code below: Snippet: :after, :be ...

What could be the reason for my Angular Material CSS file not functioning correctly?

After creating an HTML file using Angular Material, I noticed that the components' CSS files are not being applied properly. This is a snippet from my HTML file: <div class="content-container"> <div class="tree-container&quo ...

The useEffect() hook interacting with an array containing multiple levels of nested objects

Attempting to trigger useEffect() whenever there is a change in arrayWithDeeplyNestedObjects. The usage of export default compose(... is related to an offline first database solution called WatermelonDB, which updates the arrayWithDeeplyNestedObjects upon ...

Guide to embedding a React app within another React app (nesting React apps)

Is it feasible to divide a React application into two distinct apps hosted on different servers, where one app (app A) acts as a control frame for future apps B and C? I am faced with the challenge of creating a shared foundation for both apps (app A), whi ...

implement CSS styles within a JavaScript function

I am trying to change the background every second with the following code, but I am having trouble including CSS properties like centering, covering, and positioning the image properly. How can I modify this function to incorporate these settings for the ...

Every time I navigate within the application, the useReducer hook state is being reset

Each time I switch from the policy page to the test page, my reducer state changes to Count: 0. Upon inspecting the state within the ProtectedRoutes component, it appears that the state undergoes re-initialization when route changes occur. This behavior i ...

The mysterious nature of React's setState function

Situation 1 increaseScoreBy3 () { this.setState({score : this.state.score + 1}); this.setState({score : this.state.score + 1}); this.setState({score : this.state.score + 1}); } Situation 2 increaseScoreBy3 () { this.setState({score ...

Lack of consideration for height within tables positioned absolutely

In the case of an absolutely positioned element with display: table, if the height is explicitly set and the content exceeds this height, the element will adjust to wrap around the content rather than maintaining the specified height value. #main { wi ...