skip to Main Content

I am practicing React JS lately, I am fetching cast data from TMDB for the project and using the profile_path data for image source. What my problem is now since some of the cast has null as their profile_path, I could not figure out how to display that. I know Java very well but I am new to JavaScript.

I tried a person.jpeg i found on the internet to display if it is null but either my condition is wrong or i could not use the image on my folder. So it keeps displaying a broken image icon on my screen for null paths.

import imageSrc from "../assets/person.jpeg";

<Flex mt={"5"} mb={"10"} overflow={"scroll"} gap={"5"}>
      {cast?.length === 0 && <Text> No cast found</Text>}

      {cast &&
        cast?.map((item) => (
          <Box key={item?.id} minW={"150px"}>
            {cast?.profile_path === null && <Image src={imageSrc} />}
            <Image src={`${imagePath}/${item?.profile_path}`} />
            <Text>{item?.name}</Text>
            <Text fontSize={"smaller"} color={"gray.400"}>
              {item?.character}
            </Text>
          </Box>
        ))}
    </Flex>

2

Answers


  1. To display a default image when profile_path is null, you need to adjust your code so that it checks each item’s profile_path and sets the image source accordingly. Additionally, ensure that the condition and logic to handle the null profile_path are correctly implemented.

    <Image 
      src={item?.profile_path ? `${imagePath}/${item?.profile_path}` : imageSrc} 
      alt={item?.name || "No profile"} 
    />
    

    This line checks if item?.profile_path is not null. If it has a value, it constructs the image URL using imagePath and profile_path. If profile_path is null, it uses imageSrc as the source.

    Login or Signup to reply.
  2. If you want to have images on React, you can put them in your public/ folder, and then access them this way:

    if you have "image.png" in your public/ folder, you may access it like this :

    <img src="./image.png" alt="" />
    

    in other way you may import your image at the top of your code as usual:

    import logo from './logo.png';
    // Your code ...
    <img src={logo} alt="Logo" />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search