SteveBack
SteveBack

Reputation: 185

Material-UI, how to merge multiple styles with theme in typescript?

I have two styles.

in global.ts

const globalStyles = (theme: Theme) => {
  return {
    g: {
      marginRight: theme.spacing(40),
    },
  }
}

export const mergedStyle = (params: any) => makeStyles((theme: Theme) =>
  createStyles({
    ...globalStyles,
    ...params
  }),
);

in App.tsx

import * as Global from './global';

const localStyles = (theme: Theme) => {
  return {
    l: {
      marginRight: theme.spacing(20),
    },
  }
}

export default function DenseAppBar() {
  const classes = Global.mergedStyle(localStyles)();

  return (
    <div>
      <MenuIcon className={classes.l} />
      <MenuIcon className={classes.g} />
      <MenuIcon />
    </div>
  );
}

It doesn't have any compile error, but it doesn't work. How should I modify my code?

I added codesandbox.

https://codesandbox.io/s/confident-hamilton-6eect

Upvotes: 1

Views: 1757

Answers (1)

keikai
keikai

Reputation: 15146

Use a common makeStyles to generate the inner content with spread_syntax would be fine.

const style1 = (theme) => {
  return {
    a: {
      marginRight: theme.spacing(1),
    }
  }
}
const style2 = (theme) => {
  return {
    b: {
      marginRight: theme.spacing(2),
    }
  }
}
const mergedStyle = makeStyles((theme: Theme) =>
  createStyles({
    ...style1(theme),
    ...style2(theme),
  }),
);

Usage

export default function MyComponent() {
  const classes = mergedStyle();
  return (
    <>
      <div className={classes.a}></div>
      <div className={classes.b}></div>
    </>
  )
}

Try it online:

Edit friendly-goldstine-t5dhj


Update

If you want to pass params in mergeStyle function

const mergedStyle = (params) =>makeStyles((theme: Theme) =>
  createStyles({
    ...
  }),
);

usage

const classes = mergedStyle(params)();

Related question: how-to-combine-each-maked-styles-in-material-ui

Upvotes: 4

Related Questions