17
12

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 5 years have passed since last update.

Reactで画像がリンク切れの時に代替画像を表示したい時のサンプル

Posted at

imgタグonErrorに以下を記述すればOK

onError={(e) => e.target.src = 'image path'}

以下、実装するときのイメージサンプル。

Sample.js
import React, {Component} from 'react';
import noimage from './noimage.png';

class Sample extends Component {
    render() {
        <img className={'sample'}
            alt={'test'}
            src={'image path'}
            onError={(e) => e.target.src = noimage} />
    }
}

export default Sample

noimage.pngは適当なものを用意して、設置で動くはず

参考ページ

react.js Replace img src onerror

17
12
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
17
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?