Search code examples
javascriptreactjsimagematerial-table

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

enter image description here

With online Image

enter image description here

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?


Solution

  • 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.