Home > other >  React: Importing image from URL error handling
React: Importing image from URL error handling

Time:09-23

I am iterating over an API. That API contains links to pictures, that I like to visualize. I am doing it like that:

<img className={styles['picture']} src={props.flyerFront} alt="new"  />

The only problem is, that some of the links do not exist anymore (example link: "https://static.ra.co/images/events/flyer/2021/10/uk-1015-1467490-front.jpg?dateUpdated=1632838338373"). I would like to just put a predefined image instead and therefore I am asking myself, how do I catch the error?

error message from console:

enter image description here

EDIT: With the tips of the community I tried changes, which didn't help. For further clarification I put down the whole return statement below:

return (
        <div className={styles["container"]}>
            <div className={styles['pictureFrame']}>
              {typeof props.flyerFront !== 'undefined' > 0 ? 
              <img 
              className={styles['picture']} 
              src={props.flyerFront} 
              alt="new"  
              one rror={event => {
                  event.target.src={cal};
                  event.onError = null;
              }}
              /> 
              : 
              <img className={styles['picture']} src={cal}  />}
            </div>
            <div className={styles['name']}>{props.title}</div>
            <div className={styles['date']}>| Date: {props.date}</div>
            <div className={styles['plus']}>
              <img src={plus} onClick={handleClick} />
            </div>
        </div>
      )

SOLUTION:

<img className={styles['picture']} src={props.flyerFront ? props.flyerFront : cal} alt="new"  /> 

CodePudding user response:

try to import and call your image differently :

import foto from '/assets/images/foto.png';

CodePudding user response:

Try to use error event, it's built-in event.

onError={event => {
    event.target.src = "https://default-image-link-goes-here"
    event.onerror = null
}}

CodePudding user response:

You can try:

src={props.flyerFront ? props.flyerFront : "default image here"} 
  • Related