2
5

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 + Typescript で 画像を表示する方法

Last updated at Posted at 2021-03-30

過去にHTML・CSSでWebページを作成したことがある方だと
Reactでの画像の表示方法に戸惑う方がいると思うので 本記事で概要と解決方法を記載します

概要

Reactと 一般的なWebサイトでは レンダリング方式が異なります

一般的なWebサイトの場合

WebサーバーにホストしてあるHTMLのURLにアクセスがあったら
Linkタグ(CSS・画像など) を解釈してページを表示します

Reactの場合

  1. なにも書かれていない index.html を表示します
    (なにか書かれていてもいい)

  2. なにも書かれていない index.html の内容を
    Reactで生成したJavascriptによって変更することで 文章や画像を表示します
    (SPAと呼ばれる技術)

解決方法

Reactでは画像を事前にimportする必要があります

この例では 5行目で画像をimportして 11行目でimportした画像を設定しています

import React from "react";

import "./Demo.css";

import FemaleWorkerCheckingData from "../images/female-worker-checking-data.png";

const Demo: React.FC = () => {
  return (
    <div className="Demo">
      <div>Demo</div>
      <img src={FemaleWorkerCheckingData} alt="female-worker-checking-data.png" />
    </div>
  );
};
export default Demo;
2
5
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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?