Cannot read property of undefined (read 'split') TypeError: Cannot read property of undefined (read 'split')
P粉094351878
2023-07-28 20:05:15
<p>I'm trying to get the release year from the release_date (as props) passed to a React function component, but I'm getting a string undefined error. </p>
<pre class="brush:php;toolbar:false;">const Banner = ({ backdrop_path, poster_path ,title,release_date}) => {
return (
<div
className="bg-cover bg-center"
style={{
backgroundImage: `url('https://image.tmdb.org/t/p/original${backdrop_path}')`,
}}
>
<div className="bg-sky-200/80">
<div className="flex flex-nowrap p-12">
<PosterCard poster_path={poster_path} />
<div className="grow px-8">
<div className="text-4xl text-white font-bold">
<a className="hover:cursor-pointer hover:text-gray-200">{title}</a> ({release_date.split("-")[0]})
</div>
</div>
</div>
</div>
</div>
);
};
export default Banner;</pre>
<p>When I use release_date directly, it renders fine, no problem. But when I apply any method on string it returns undefined. (release_date is a string, such as "2023-07-18")</p>
I recommend adding a condition to ensure I don't have empty brackets (e.g. if your data get returns empty).