Home > Blockchain >  How to pass sx prop to Icons with menu.map function in material ui?
How to pass sx prop to Icons with menu.map function in material ui?

Time:09-18

I'm trying to map out a menu with icons in Material UI

its working, but I do not understand how to pass the sx prop into the Icon when using the map function.

this is an example

export const Menuitems = [
    {
      name: 'Dashboard',
      to: '/',
      text: 'dashboard',
      icon: (<DashboardIcon />),
    },
    {
      name: 'Pretest',
      to: '/pretest',
      text: 'pretest',
      icon: (<AccessibilityIcon />),
    }, 
  ]

export const ShowMainMenu = (props) => {
  return (
    <Grid item >
    <Link style={{ textDecoration: "none" }} to={props.to}>
    <Paper elevation={6}>
        {props.icon}
        <Typography fontSize={20} fontWeight={600}>{props.name}</Typography>
    </Paper>
    </Link> 
    </Grid>

in another component, I map over the Menuitems with spread like this:

 <Grid container >
  { Menuitems.map((item) => {
       return  <ShowMainMenu {...item} />
    })
  } 
 </Grid>

This works fine, but I need to change the size of the Icons with a sx prop.

I would like to have it like this:

<DashboardIcon sx={{color: '#002884' , fontSize: 80 }}/>

I would prefer not to put styling into the menu-array because I use it in many different settings, so I would like to keep it clean.

Does anyone have any suggestions on how to use the sx prop in this context?

CodePudding user response:

Instead of defining icons as jsx, you can define icons as component references like this:

export const Menuitems = [
  {
    name: "Dashboard",
    to: "/",
    text: "dashboard",
    icon: DashboardIcon
  },
  {
    name: "Pretest",
    to: "/pretest",
    text: "pretest",
    icon: AccessibilityIcon
  }
];

And then render the icons inside of ShowMainMenu component like this:

export const ShowMainMenu = (props) => {
  const IconComponent = props.icon;
  return (
    <Grid item>
      <Link style={{ textDecoration: "none" }} to={props.to}>
        <Paper elevation={6}>
          <IconComponent sx={props.iconSx} />
          <Typography fontSize={20} fontWeight={600}>
            {props.name}
          </Typography>
        </Paper>
      </Link>
    </Grid>
  );
};

And pass sx reference in your map function like this:

<Grid container>
    {Menuitems.map((item, i) => {
      return (
        <ShowMainMenu
          {...item}
          iconSx={{ color: "#002884", fontSize: 80 }}
        />
      );
    })}
</Grid>

You can take a look at this sandbox for a live working example of this approach.

  • Related