Guide to showing an image in a Material-UI X DataGrid column

As someone new to React, I recently embarked on my journey by creating a test project utilizing MUI Table, and so far it's been a success:

https://i.stack.imgur.com/clb4p.png

However, I am now looking to incorporate pagination and sortable columns when presenting my data.

To tackle this, I decided to develop another test project using MUI X DataGrid:

https://i.stack.imgur.com/WV8ZI.png

While the functionality is there, I noticed that the last column displays my HTML img code as is.

In an attempt to address this issue, I implemented a custom solution within my TopGrid.jsx component:

const wrongImgHandler = (photo) => {
  return photo && PHOTO_PATTERN.test(photo) ? photo : "female_sad.png";
};

const imgErrorHandler = ({ currentTarget }) => {
  // prevents looping
  currentTarget.onerror = null;
  currentTarget.src = "male_sad.png";
};

const columns = [
  {
    field: "elo",
    headerName: "Elo",
    type: "number",
    width: 90,
  },
  {
    field: "given",
    headerName: "First name",
    width: 150,
  },
  {
    field: "photo",
    headerName: "Photo",
    sortable: false,
    width: 160,
    valueGetter: (params) =>
      `<img
        src=${wrongImgHandler(params.row.photo)}
        className="avatar"
        onError=${imgErrorHandler}
      />`,
  },
];

I would greatly appreciate any guidance on how to properly display an img element with an onError handler in the MUI X DataGrid.

Answer №1

Appreciate the help @super, the renderCell feature is exactly what I needed:

https://i.stack.imgur.com/LrgvX.png

function DisplayImage({ image }) {
  const fixErrorImage = (image) => {
    return image && IMAGE_PATTERN.test(image) ? image : "default_image.png";
  };

  const errorHandler = ({ currentTarget }) => {
    // stop error looping
    currentTarget.onerror = null;
    currentTarget.src = "alternative_image.png";
  };

  return (
    <img
      src={fixErrorImage(image)}
      className="display-image"
      onError={errorHandler}
    />
  );
}

DisplayImage.propTypes = {
  image: PropTypes.string.isRequired,
};

const columns = [
  {
    field: "rating",
    headerName: "Rating",
    type: "number",
  },
  {
    field: "username",
    headerName: "Username",
    width: 200,
  },
  {
    field: "profilePic",
    headerName: "Profile Picture",
    align: "center",
    sortable: false,
    renderCell: (params) => <DisplayImage image={params.row.profilePic} />,
  },
];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Importing vs Referencing Videos in Next.js - What is the Best Practice for Video Integration in Next.js?

I'm looking to use a video as a background in my banner design. Typically, with images in Next.js, I would import them and then pass the import as src (for example: import img from '@images/about-us-page/img.svg'). However, when attempting ...

What is the best approach to display a fluctuating price depending on specific options chosen in Next.js?

When working with 2 different select tags and rendering images based on the selection, I also want to display a price determined by the options chosen. For instance, selecting "Your Current Division" as Iron and "Your Desire League" as Bronze/Silver/Gold s ...

What is the best way to incorporate web components into a React Js project?

I am currently unfamiliar with web components. My main goal is to integrate Google Material Components into my React.js project. Google Material Web Component can be found here: https://github.com/material-components/material-components-web Is there a ...

How do I make a component in React delete itself from a page when its internal state changes?

For instance: {!loading ? (data.map((v, i) => { return <Card key={i} title={v.name} image={v.pictures.sizes[4].link}} /> }) These cards are displayed as a series of components on the main screen. Each card ...

Verify the occurrence of an element within an array inside of another array

Here is the scenario: const arr1 = [{id: 1},{id: 2}] const arr2 = [{id: 1},{id: 4},{id: 3}] I need to determine if elements in arr2 are present in arr1 or vice versa. This comparison needs to be done for each element in the array. The expected output sho ...

Retrieve the id for the chosen user name within a function that contains an array of objects

const userList = [ {name:"jonh" ,id:EAD1234}, {name:"peter" ,id:EAD1235}, {name:"matt" ,id:EAD1236}, {name:"henry" ,id:EAD1237}, ] In the array above, there are various users with their respective IDs. The goal is t ...

What sets Layout apart from Template in Nextjs Version 13?

Can anyone clarify the distinction for me? I'm under the impression that a layout and template are interchangeable terms. ...

The navigation bar in React Router is interfering with the loading of other components

Currently, I am in the process of setting up a simple navigation bar that consists of basic buttons without any complex functionality. However, I have encountered an issue where placing the navbar inside the switch prevents other components from loading ...

how to share global variables across all components in react js

Operating a shopping cart website requires transmitting values to all components. For instance, when a user logs into the site, I save their information in localStorage. Now, most components need access to this data. My dilemma is whether I should retriev ...

Adjusting the height and paddingTop of the Dialog component in Material-UIredirectTo:

I am attempting to dynamically adjust the height of a dialog box in order to ensure all content is fully displayed within it. Additionally, I am looking to decrease the top padding of the modal to maximize available space.... Any suggestions on how I can ...

Encountering issues with implementing router.push in Reactjs

Currently, I am working on ReactJS and utilizing Next.js. My current task involves refreshing the page (using routes), but I encountered an error message stating: Error: No router instance found. You should only use "next/router" inside the client-side of ...

Adjust the text to align with the available space while maintaining the original motion effect

My Next.js project has the following structure: . ├── media │   └── img.jpg ├── package.json ├── package-lock.json ├── postcss.config.js ├── src │   ├── components │   │   └── AnimatedCharacte ...

Arrangement of items in a grid featuring a row of three items, each with an automatic width

I'm facing challenges with achieving a specific layout: My goal is to have the left and right elements automatically adjust their width to cover all the empty space on either side of the center element. Here is what I've tried so far, but I&apo ...

What causes material-ui styling to flicker while moving between pages in Next.js?

Visit this link for more information Experience a unique button styling transition when moving from one page to another. Check out the code snippet here: Explore the code on GitHub ...

The state update is paused by one state

Feeling a bit lost here, could be a beginner's mistake. Attempting to replicate the game of chess. Encountering a delay issue in my code.. basically, when I click on a square to display the possible moves for a piece, they only show up correctly aft ...

One may wonder about the distinction between running `npm i` and `npm i <package name>`

I am currently working on a React Native project where the package.json contains a specific version of react. However, I am hesitant to run npm i for fear that it will install the latest version of react instead. I wonder if running npm i will respect th ...

Updating a React state using a matrix in a simple yet effective way

I'm struggling with figuring out how to save input values from the table generated by the code below: createTable = () => { let table = []; for (let i=0; i<this.state.rows; i++) { let rowID = `r${i}`; let cell = []; for (let j=0; j<this ...

Tips for creating a stylish ReactJs Header component that stays fixed at the top of the page

Having an issue with my Header component - I want it to remain fixed at the top while scrolling down. Here's the current code: I've attempted using "position = fixed", but it caused my header to resize. Then, I tried setting its width to "width ...

How to effectively manipulate nested arrays in JavaScript without altering their references

Welcome everyone, I've been working on a project using next.js and I've encountered an issue with filtering posts. The filter function works perfectly when the posts are in a simple array like ObjChild. However, I have another section on my site ...

Elevate the appearance of your UI with stylish Material text

I'm struggling to customize a material-ui textfield to achieve my desired look. I simply want a clean and plain white input field with the standard MUI animations. It's important that the textfield always has a white background and the text appea ...