0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ReactNative】リモートの画像を上手に表示するTips

Last updated at Posted at 2025-04-02

はじめに

こんにちは、梅雨です。

今回は、ReactNative においてリモートの画像を簡単に表示できるようにするカスタムコンポーネントの設計を紹介します。

カスタムコンポーネント

結論から話すと、以下のようなカスタムコンポーネントを作成しました。

import { useState } from "react";
import { Image, ImageStyle, StyleProp } from "react-native";

const RemoteImage = ({ src, style }: { src: string; style?: StyleProp<ImageStyle> }) => {
  const [aspectRatio, setAspectRatio] = useState(1);
  return (
    <Image
      source={{ uri: src }}
      style={[
        { aspectRatio, marginHorizontal: "auto" },
        aspectRatio > 1 ? { width: "100%" } : { height: "100%" },
        style
      ]}
      onLoad={(e) => {
        const { width, height } = e.nativeEvent.source;
        setAspectRatio(width / height);
      }}
    />
  );
};

export default RemoteImage;

ポイントとしては、

  • aspectRatio をステートとして保持
  • 画像ロード時にアスペクト比を計算してステートにセット
  • Props でスタイルを受け取り上書き可能

のようになっています。

使用例

実際の使い方は以下のようになります。
src には画像の URL を、style には通常のコンポーネントのようにスタイルを記述することができます。

<RemoteImage src="https://picsum.photos/600/400" style={{ borderRadius: 10 }} />
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?