Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically load react-icons into component

Tags:

reactjs

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?

like image 211
Ronald Zwiers Avatar asked Mar 24 '26 19:03

Ronald Zwiers


2 Answers

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>
 );
};
like image 106
vijayst Avatar answered Mar 26 '26 08:03

vijayst


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>
// ...
}
like image 20
Shams Wali Sowmo Avatar answered Mar 26 '26 09:03

Shams Wali Sowmo