简体   繁体   中英

How to pass mui-icon component as props to another component?

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 class="sidebar-icon group">
      <AddIcon/>
    </div>
  );
};

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

export default SideBarPanel;

在此处输入图像描述

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

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 class="sidebar-icon group">
      {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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM