Viewing Mesages

Viewing an image message

Once uploaded, your message can displayed simply by fetching the file from the FileRepository and use the file.fileUrl property to display the image.

Here's a small React component which achieves that:

import React, { useEffect, useState } from 'react';
import { FileRepository } from '@amityco/js-sdk';

const ImageMessageContent = ({ data, fileId }) => {
  const [file, setFile] = useState();

  useEffect(() => {
    const liveObject = FileRepository.getFile(fileId);

    liveObject.on('dataUpdated', setFile);
    liveObject.model && setFile(liveObject.model);

    return () => liveObject.dispose()
  }, [fileId])

  return (
    <>
      {data?.caption && <p>{data!.caption}</p>}
      {file && <img src={file.fileUrl} />}
    </>
  )
}

Viewing various types of message

In the context of a chat room, messages can sometimes be of type image or file, or simply text. The simpliest strategy is to have one renderer per type, and use them when appropriate.

You'll need:

  1. A specific renderer for each type (TextContent, ImageContent, and FileContent)

  2. A dictionary to match the message.type to those renderers

  3. A single-point-of-entry component MessageContent.

import React, { useEffect, useState } from 'react';
import { FileRepository, MessageType } from '@amityco/js-sdk';

// renders a text message
const TextContent = ({ data, fileId }) => {
  return data?.text ? <p>{data!.text}</p> : null;
}

// renders an image message
const ImageContent = ({ data, fileId }) => {
  const [file, setFile] = useState();

  useEffect(() => {
    const liveObject = FileRepository.getFile(fileId);

    liveObject.on('dataUpdated', setFile);
    liveObject.model && setFile(liveObject.model);

    return () => liveObject.dispose()
  }, [fileId])

  return (
    <>
      {data?.caption && <p>{data!.caption}</p>}
      {file && <img src={file.fileUrl} />}
    </>
  )
}

// renders a file message
const FileContent = ({ data, fileId }) => {
  const [file, setFile] = useState();

  useEffect(() => {
    const liveObject = FileRepository.getFile(fileId);

    liveObject.on('dataUpdated', setFile);
    liveObject.model && setFile(liveObject.model);

    return () => liveObject.dispose()
  }, [fileId])

  return (
    <>
      {file && <a href={file.fileUrl} download>{file.attributes.name}</a>}
      {data?.caption && <p>{data!.caption}</p>}
    </>
  )
}

// a Record<MessageType, MessageRenderer>
const MessageRenderers = {
  [MessageType.Text]: TextContent,
  [MessageType.Image]: ImageContent,
  [MessageType.File]: FileContent,
}

// Your React 'switch/case' component
const MessageContent = ({ type, data, fileId, isDeleted }) => {
  if (isDeleted)
    return 'message deleted';

  const Renderer = MessageRenderers[type]

  return Renderer
    ? <Renderer data={data} fileId={fileId} />
    : 'unsupported message type';
}

Last updated