简体   繁体   中英

ReactJS - Image is not shown in a custom column of Material-Table

I'm working on material-table to render a custom column with images just like this example in the official docs. But there is a little problem. The example online image from githubusercontent.com is working perfectly fine but if I give the path of a local image on my machine it don't work.

With Image on my machine

在此处输入图像描述

With online Image

在此处输入图像描述

There is no problem with image dimensions or file extension etc. as I downloaded the same image from githunusercontent.com and that is not working on local machine as well.

Edit

Just I saw a little error message in the console saying

Not allowed to load local resource 'file-path' What to do now?

To show the image from the local machine you can do it in the following way:

App.js file:

import React from 'react';

import MaterialTable from 'material-table';

export default class App extends React.Component {
  render() {
    return (
      <MaterialTable
        title="Render Image Preview"
        columns={[
          { title: 'Avatar', field: 'imageUrl', render: rowData => <img src={require('./img.jpeg')} style={{ width: 40, borderRadius: '50%' }} /> },
          { title: 'Name', field: 'name' },
          { title: 'Surname', field: 'surname' },
          { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
          {
            title: 'Birth Place',
            field: 'birthCity',
            lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
          },
        ]}
        data={[
          { name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63, imageUrl: 'https://avatars0.githubusercontent.com/u/7895451?s=460&v=4' },
          { name: 'Zerya Betül', surname: 'Baran', birthYear: 2017, birthCity: 34, imageUrl: 'https://avatars0.githubusercontent.com/u/7895451?s=460&v=4' },
        ]}
      />
    )
  }
}

Note: I've downloaded the image and renamed it as img.jpeg from the URL you've given here and kept it in the same directory where App.js file is located.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM