3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

react にて、画像リンク切れの際、imgタグを非表示にする

Posted at

通常のhtmlにおいては、onerrorハンドラにてリンク切れのimgタグを非表示にできます。

<img src="original.png" alt="title" onerror="this.style.display='none'"/>

reactではこれができないため、以下のようにonErrorハンドラを作成します。

<img src={`${process.env.PUBLIC_URL}/logo192_.png`} onError={e => e.target.style.display = 'none'} />

サンプル

🚀以下のサンプルは、create-react-app直後のApp.jsを編集したものです。

App.js
import React from 'react';

function App() {
  return (
    <div className="App">
      <img border="1" src={`${process.env.PUBLIC_URL}/logo192.png`} />
      <img border="1" src={`${process.env.PUBLIC_URL}/logo192_.png`} />
      <img border="1" src={`${process.env.PUBLIC_URL}/logo192_.png`} onerror="this.style.display='none'" />
      <img border="1" src={`${process.env.PUBLIC_URL}/logo192_.png`} onError={e => e.target.style.display = 'none'} />
    </div>
  );
}

export default App;

参考

📖Hide broken image link in Semantic UI React
📖リンク切れの時に代替画像を表示したいときはこちら

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?