Displaying images in React and Airtable: What's the trick?

I’m working on a React project with Airtable and I’m having trouble showing an image. My logo file is in the same folder as my main JavaScript file but it’s not showing up. I’ve tried a few ways to link the image but nothing seems to work. Here’s what I’ve attempted:

<img src={window.location.origin + './myicon.png'} />
<img src={'./myicon.png'} />

My project setup is pretty simple:

project-root/
  ├── src/
  │   ├── main.js
  │   └── myicon.png

I’m not using webpack so I can’t import the image directly. Here’s a snippet of my current code:

import React from 'react';
import { initializeBlock, useBase } from '@airtable/blocks/ui';

function MyComponent() {
  return (
    <div>
      <h2>Greetings from Airtable!</h2>
      <img src={'./myicon.png'} />
    </div>
  );
}

export default MyComponent;

Any ideas on how to get this working? I’m pretty stuck!

I’ve dealt with this issue before in Airtable Blocks. The problem is that Airtable’s runtime environment doesn’t handle local file paths like a typical web server would. Instead, you need to use Airtable’s own asset handling system.

Here’s what I’d suggest:

  1. Upload your image to Airtable as an attachment in a dedicated table.
  2. Fetch the attachment URL using Airtable’s API.
  3. Use that URL in your img tag.

Here’s a quick example of how you might implement this:

function MyComponent() {
  const base = useBase();
  const [iconUrl, setIconUrl] = useState('');

  useEffect(() => {
    const fetchIcon = async () => {
      const assetsTable = base.getTableByName('Assets');
      const query = await assetsTable.selectRecordsAsync();
      const iconRecord = query.records[0];
      setIconUrl(iconRecord.getCellValue('Icon')[0].url);
    };
    fetchIcon();
  }, []);

  return (
    <div>
      <h2>Greetings from Airtable!</h2>
      {iconUrl && <img src={iconUrl} alt='My Icon' />}
    </div>
  );
}

This approach should work reliably within the Airtable Blocks environment.

I’ve encountered similar issues when working with React and Airtable. The problem likely stems from how React handles static assets. Here’s what worked for me:

Try moving your image to a ‘public’ folder at the root of your project. Then, reference it using the public URL path:

<img src={'/myicon.png'} alt='My Icon' />

If that doesn’t work, you might need to use Airtable’s asset handling. Upload the image to Airtable, then fetch it using their API. Something like:

const [iconUrl, setIconUrl] = useState('');

useEffect(() => {
  // Fetch the attachment URL from your Airtable base
  const fetchIcon = async () => {
    const record = await base.getTable('YourTable').getRecord('RecordId');
    setIconUrl(record.getCellValue('IconField')[0].url);
  };
  fetchIcon();
}, []);

// Then in your JSX
<img src={iconUrl} alt='My Icon' />

This approach has been more reliable for me when working with Airtable and React.