Search code examples
reactjsmaterial-uireact-admin

Conditional styling using `sx` in React-Admin


Since makeStyles is deprecated: https://mui.com/system/styles/basics/. I'm trying to implement new approach with sx prop.

I'm having trouble understanding how to use it with React-Admin components.

Let's say I have a list of Logs which can be Error, Warning, or Info under type field, and I want to color it appropriately.

I've tried something like this:

const LogList = ({ permissions, ...props }) => {
  return (
    <List
      {...props}
      title="Logs"
      filters={<LogFilter />}
      perPage={25}
      bulkActionButtons={false}
    >
      <Datagrid rowClick="show">
        <TextField
          source="type"
          label="Type"
          sx={ record.type === "Error" ? {color: "red"} : {color: "blue"}}
        />
        <TextField
          source="description"
          label="Description"
        />
        <DateField
          source="createdAt"
          label="Created At"
        />
      </Datagrid>
    </List>
  );
};

But record cannot be used in sx.

Any ideas how to make it work?


Solution

  • You need to access the record, for example with the useRecordContext() hook:

    import { useRecordContext, TextField } from 'react-admin'
    ...
    const TypeField = () => {
      const record = useRecordContext()
    
      return (
        <TextField
          source="type"
          label="Type"
          sx={{ color: record?.type === "Error" ? "red" : "blue" }}
        />
      )    
    }