简体   繁体   中英

How to conditionally render a data url in Reactjs

I am trying to conditionally render a data url based on the condition that the svg file from a folder does not exist. I have a whole bunch of svg files that are coming in and is being brought in dynamically by the name of the file. There are some svg's that do not exist and so I would need to dynamically render a circle shaped icon with a capital text as a placeholder for the image. I currently have:

I know there is a way, but I havent been a able to figure this out and there arent any similar solutions online. Would really appreciate any help. Thanks!

Note: In case you are wondering how I am able to render svg files by using the img="" method, its because I did some configurations and added some packages to do the job.
 

You just need to use the onError prop of the img element. The idea is to swap the src prop with your fallback image whenever the onError is called, and it's going to be called when an image does not exist. Here is a Sandbox and the code:

import { Fragment, useRef } from "react";
import "./styles.css";

const img_array = [
  "images/icon1.png",
  "images/icon2.png",
  "https://lesspestcontrol.com.au/wp-content/uploads/green-tick.png"
];

const fallback_img =
  "https://cdn.iconscout.com/icon/premium/png-256-thumb/broken-link-3-503014.png";

export default function App() {
  const swapDefaultImage = (e) => (e.target.src = fallback_img);

  return (
    <div>
      {img_array.map((src, i) => (
        <Fragment key={i}>
          <img alt={`${src}`} onError={swapDefaultImage} src={src} />
          <br />
        </Fragment>
      ))}
    </div>
  );
}

Here you have an array of 3 images, 2 of which are not where they're supposed to be and thus will be replaced with the fallback image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM