Search code examples
react-admin

How do I change the size of an image in an ImageField?


When I change the image width and height using styles only the column width changes. The image size is not affected.

Any ideas?

With no styles Screen Shot 2019-04-06 at 2 49 47 PM

With styles Screen Shot 2019-04-06 at 2 49 32 PM

Repro CodeSandbox (https://codesandbox.io/embed/54r440jp8k)

import React from "react";
import { Datagrid, ImageField, List, TextField } from "react-admin"; // eslint-disable-line import/no-unresolved
import { withStyles } from "material-ui/styles";

const styles = {
  image: {
    width: "20px",
    height: "20px"
  }
};

export const PostList = withStyles(styles)(({ classes, ...props }) => (
  <List {...props}>
    <Datagrid>
      <ImageField source="image.url" className={classes.image} />
      <TextField source="id" />
      <TextField source="title" />
    </Datagrid>
  </List>
));

Using

  • React-admin version: 2.8.5
  • React version: 16.8.6
  • Browser: Chrome Version 73.0.3683.86 (Official Build) (64-bit)

Solution

  • Building off Shawn K's post (thanks for the direction!)...

    I believe this is a complete component (I've tested the classes override from the <List /> component and it works. This also follows react-admin and material-ui docs (and standards). However, I am still quite new to this so please reply with any corrections and I will update this.

    import React from "react";
    import PropTypes from "prop-types";
    import { withStyles } from "@material-ui/core/styles";
    import classNames from "classnames";
    
    import Avatar from "@material-ui/core/Avatar";
    
    const styles = {
      img: {
        width: 36,
        height: 36
      },
      root: {}
    };
    
    const ListAvatar = ({ className, record, source, classes }) => {
      return (
        <Avatar
          src={record[source]}
          className={classNames(classes.root, classes.img, className)}
        />
      );
    };
    
    ListAvatar.propTypes = {
      label: PropTypes.string,
      record: PropTypes.object,
      source: PropTypes.string.isRequired,
      classes: PropTypes.object.isRequired,
      className: PropTypes.string
    };
    
    export default withStyles(styles)(ListAvatar);
    

    Reference docs