I am trying to dynamically load react-icons into a component. The code is looking like this:
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import * as MaterialDesign from 'react-icons/md';
const styles = {
default: {
flexDirection: 'column',
alignItems: 'center'
},
inline: {
flexDirection: 'row'
}
};
const StyledTabs = styled.button`
display: flex;
cursor: pointer;
color: ${props => props.color};
${props => styles[props.type]}
`;
const Tabs = ({ icon, type, text, color }) => {
return (
<StyledTabs icon={icon} type={type} text={text} color={color}>
<span>
<MaterialDesign.MdHome />
</span>
<span>{text}</span>
</StyledTabs>
);
};
Tabs.propTypes = {
/** Text of tab */
text: PropTypes.string.isRequired,
/** Text of tab */
type: PropTypes.oneOf(['default', 'inline']),
color: PropTypes.string,
icon: PropTypes.string
};
Tabs.defaultProps = {
type: 'default',
color: '#000',
icon: ''
};
/**
* @component
*/
export default Tabs;
So i want the name of the react-icon in the property icon and place the string in <MaterialDesign.MdHome /> MdHome will be the string given in the property icon e.g. MaterialDesign.{icon} any help with getting this done?
Try this:
const Tabs = ({ icon, type, text, color }) => {
const mdIcon = MaterialDesign[icon];
return (
<StyledTabs icon={icon} type={type} text={text} color={color}>
<span>
<mdIcon />
</span>
<span>{text}</span>
</StyledTabs>
);
};
This works fine for me using props:
import * as MaterialDesign from "react-icons/md";
const DashboardSidebarButton = ({ icon, text }) => {
// ...
<div className="text-3xl bg-red-500">{React.createElement(MaterialDesign[`${icon}`])}</div>
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With