Search code examples
javascriptreactjsreact-icons

Rendering a component using a variable in React


I have a list of react-icons passed through props in a "Card Component". In my Card component's render method, I have something like this:

render() {
  ...
  {
     this.props.icons.map(icon => {
        return (
          <div className="icon-square">
            /*   What should I do here so I render the "icon" variable"   */
          </div>
        )
     })
   }
}

Note: The list consists of react-icons which are React components themselves.

I tried a lot of things, but I can't quite figure out how I can render the icon. It would be awesome if someone could help me. Thank you


Solution

  • Let say you've passed a list of an icon like

    import { FaBeer, FaBug, FaAnchor, FaCoffee } from 'react-icons/fa';
    
    const icons = [FaBeer, FaBug, FaAnchor, FaCoffee];
    
    ReactDOM.render(
        <CardComponent icons = {icons} />,
        document.querySelector('root')
    };
    

    CardComponent.js

    class CardComponent extends React.Component{
    ...
    
    render() {
    
      // Icon is a Component
      return (
        this.props.icons.map((Icon) => {
         return <Icon />
        });
      )
    
     }
    }