Search code examples
reactjstypescriptmaterial-uiemotion

How to use custom properties from MUI theme object with custom props in emotion styled components?


I have added a custom object named fTokens to the MUI theme via Module augmentation in TypeScript

This is how my theme.d.ts looks like

declare module "@mui/material/styles" {
  interface FPalette { ...
  }

  interface FTokens { ...
  }

  interface FSpacing { ...
  }

  interface Theme {
    fPalette: FPalette;
    fTokens: FTokens;
    fSpacing: FSpacing;
  }

  interface ThemeOptions {
    fPalette: Partial<FPalette>;
    fTokens: Partial<Tokens>;
    fSpacing: Partial<FSpacing>;
  }
}

And I am trying to pass a custom prop rowId to TableRow of MUI

import MUITableRow, { TableRowProps as MUITableRowProps } from "@mui/material/TableRow";
import { styled } from "@mui/system";

interface TableRowProps {
  rowId: number;
}

const TableRow = styled(MUITableRow)<TableRowProps>(({ theme }) => ({
  backgroundColor: theme.fTokens.surfaceHigh,
}));

export default TableRow;

I am getting TypeScript error as Property 'fTokens' does not exist on type 'Theme'.ts(2339)

UPDATE - I tried Type assertion using as keyword that is working for me but I don't know if this is the most elegant way to solve this?

const TableRow = styled(MUITableRow)<TableRowProps>(({ theme, rowId }) => ({
  backgroundColor:
    rowId % 2 === 0
      ? (theme as Theme).fTokens.surfaceHigh
      : (theme as Theme).fTokens.surfaceHighest,
}));

Solution

  • try import styled from '@mui/material/styles', not '@mui/system'

    import { styled } from '@mui/material/styles';

    doc: https://mui.com/system/styled/#import-path