skip to Main Content

I am trying to get release year from release_date(passed as props) in react functional component ,but i am getting that the string is undefined .

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;

When i used release date as it is ,then it renders properly ,no issues .But when i apply any method on string it gives undefined. (realease date is string as "2023-07-18")

2

Answers


  1.  <a className="hover:cursor-pointer hover:text-gray-200">{title}</a> ({release_date?.split("-")[0]})
    

    This line of code will not give you undefined. you just need to check by adding ? that release_data is not undefined.

    Login or Signup to reply.
  2. I would suggest to add a condition just to make sure I do not have empty parentheses (in case your data fetching returns nothing for example):

    <a className="hover:cursor-pointer hover:text-gray-200">{title}</a>
    {release_date && ` (${release_date.split("-")[0]})`}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search