I’ve made a spring API and called that for Carousel
effect in Hero.js
file. It worked completely fine till last night.
But today while i’ve restarted my project[it’s showing error
Uncaught TypeError: Cannot read properties of undefined (reading ‘0’)
I don’t understand where the error occurs.
Hero.js
import './Hero.css';
import Carousel from 'react-material-ui-carousel';
import { Paper } from '@mui/material';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCirclePlay } from '@fortawesome/free-solid-svg-icons';
import {Link, useNavigate} from "react-router-dom";
import Button from 'react-bootstrap/Button';
import MovieData from './MovieData';
const Hero = ({movies}) => {
const navigate = useNavigate();
function reviews(movieId)
{
navigate(`/Reviews/${movieId}`);
}
return (
<div className ='movie-carousel-container'>
<Carousel>
{
movies?.map((movie) =>{
return(
<Paper key={movie.imdbId}>
<div className = 'movie-card-container'>
<div className="movie-card" style={{"--img": `url(${movie.backdrops[0]})`}}>
<div className="movie-detail">
<div className="movie-poster">
{/* movie poster to movie details */}
<img
variant ="info"
onClick={() => reviews(movie.imdbId)}
src={movie.poster}
alt=""
/>
</div>
<div className="movie-title">
<h4>{movie.title}</h4>
</div>
<div className="movie-buttons-container">
<Link to={`/Trailer/${movie.trailerLink.substring(movie.trailerLink.length - 11)}`}>
<div className="play-button-icon-container">
<FontAwesomeIcon className="play-button-icon"
icon = {faCirclePlay}
/>
</div>
</Link>
<div className="movie-review-button-container">
<Button variant ="info" onClick={() => reviews(movie.imdbId)}>Reviews</Button>
</div>
</div>
</div>
</div>
</div>
</Paper>
)
})
}
</Carousel>
{/* Movie Details with Watchlist and Booking Button */}
<div className='home'>
<MovieData/>
</div>
</div>
)
}
export default Hero
2
Answers
The error shows that the error is occuring at line 28 of your file, this line:
<div className="movie-card" style={{"--img": `url(${movie.backdrops[0]})`}}>
This suggests that the movie object with backdrops array cannot be accessed at index 0 (so backdrops isn’t populated). Without seeing the rest of the code it’s difficult to know why, but check the component that renders the Hero component and ensure that all movies object contains an array of backdrops.
Try optional chaining with Elvis Operator
?.
to get objects within objects.or