1

I am doing a clone of Netflix using React.js for learning React.js. I integrated an API from TMDb and for the case of banner image , name , and description , I have an array of 20 Objects which contains all details of 20 movies , and when the page is refreshed , I need to change the Banner into another random movie in the array. I don't Know how to select a random object by its number. Please Help Me To do this.

Here Is My Code :

import React, { useState } from 'react'
import './Banner.css'
import {useEffect} from 'react'
import {API_KEY,imageUrl} from '../../Constants/Constants'
import axios from '../../Axios'

function Banner() {
    const [movie, setMovie] = useState()
    useEffect(() => {
        axios.get(`trending/all/week?api_key=${API_KEY}&language=en-US`).then((response)=>{
            console.log(response.data);
            setMovie(response.data.results[11])
        })
    }, [])
    return (
        <div className="banner" style={{backgroundImage:`url(${movie ? imageUrl+movie.backdrop_path : ""})`}}>
            <div className="content">
                <h1 className="title">{movie ? movie.title : ""}</h1>
                <div className="banner-buttons">
                    <button className="button">Play</button>
                    <button className="button">My List</button>
                </div>
                <h1 className="description">{movie ? movie.overview : ""}</h1>
            </div> 
            <div className="fade-bottom"></div>                               
        </div>
    )
}

export default Banner

1 Answer 1

2

You can use Math.random() which gives you a random number between 0 and 1. You then multiply it by the length of the resulting array and you round it to the lower integer using Math.floor(). You now have a random integer in the proper range that can be used to extract an element from the array itself.

const results = response.data.results
const newIndex = Math.floor(Math.random() * results.length)

setMovie(results[newIndex])
Sign up to request clarification or add additional context in comments.

2 Comments

But It Says 'response' is not defined ??
I based that on your example code: setMovie(response.data.results[11]). You should be able to adjust it accordigly to your actual data structure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.