LoginSignup
6
3

More than 1 year has passed since last update.

React + axios で画像を取得して表示させる

Posted at

はじめに

Django REST Framework で画像を返す API を作成で画像を返す API を作成したので、React アプリで画像を取得して表示させてみる。

axios のインストール

以下コマンドで axios をインストールする。

$ npm install axios

コンポーネントの作成

画像を取得し、それを表示するコンポーネントを作成する。ここでは例として、React Logo を取得する。コードは以下。

AxiosTest.js
import React, { useState, useEffect } from 'react'
import axios from 'axios'

const AxiosTest = () => {

    const [image, setImage] = useState()

    useEffect(() => {
        axios.get('https://logos-download.com/wp-content/uploads/2016/09/React_logo_wordmark.png')
            .then(res => {
                setImage(res.data)
            })
    }, [])

    return (
        <div>
            <img src={image} width="500" />
        </div>
    )
}

export default AxiosTest;

しかし、アプリを起動してみると以下のように適切に画像が表示されない。

noImage.png

解決法を調査したところ、Axios serving png image is giving broken image に解決策があった。修正したコードが以下。

AxiosTest.js(revised)
import React, { useState, useEffect } from 'react'
import axios from 'axios'

const AxiosTest = () => {

    const [image, setImage] = useState()

    useEffect(() => {
        axios.get(
            'https://logos-download.com/wp-content/uploads/2016/09/React_logo_wordmark.png',
            {responseType: 'blob',}
            )
            .then(res => {
              setImage([URL.createObjectURL(res.data)])
            })
    }, [])

    return (
        <div>
            <img src={image} width="500" />
        </div>
    )
}

export default AxiosTest;

適切に表示させることができた。

image.png

6
3
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
6
3