Home > Software engineering >  How to pass mui-icon component as props to another component?
How to pass mui-icon component as props to another component?

Time:08-13

import React from "react";
import "./SideBarPanel.css";
import AddIcon from "@mui/icons-material/Add";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

const SideBarIcon = () => {
  return (
    <div >
      <AddIcon/>
    </div>
  );
};

const SideBarPanel = () => {
  return (
    <div className="sidebar-icons">
      <SideBarIcon />
      <SideBarIcon />
    </div>
    
  );
};

export default SideBarPanel;

enter image description here

I want to pass the ExpandMoreIcon into the second SideBarIcon component.

CodePudding user response:

You should be able to pass a component down to a child component via props just like a normal variable. There is one caveat though: when you render it in the child component, you have to ensure it is named with first letter a capital letter.

import React from "react";
import "./SideBarPanel.css";
import AddIcon from "@mui/icons-material/Add";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

const SideBarIcon = (props) => {
  const {icon: Icon} = props;
  return (
    <div >
      {Icon && <Icon />}
      <AddIcon/>
    </div>
  );
};

const SideBarPanel = () => {
  return (
    <div className="sidebar-icons">
      <SideBarIcon />
      <SideBarIcon icon={ExpandMoreIcon} />
    </div>
    
  );
};

export default SideBarPanel;

Here I assign icon to a new variable Icon while destructuring. This is important because <icon /> will not work because the first letter is not capitalized.

Sandbox

Source: https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized

CodePudding user response:

I would write <Icon /> as a child of <SideBarIcon />. You can have it as optional child. Also in this case you would approach component composition, which is recommended by React.

  • Related