Rendering a component using a variable in React

Viewed 803

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

4 Answers

If the icon is a react component, then:

this.props.icons.map(Icon => {
        return (
          <div className="icon-square">
            <Icon/>
          </div>
        )
     })

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 />
    });
  )

 }
}

Here is two difference for use your icon, If you pass as a JSX you should use {icon} But if you pass as a component you should use like this <Icon/>

I think wrapping you need to just put icon is {}

render() {
  ...
  {
     this.props.icons.map(icon => {
        return (
          <div className="icon-square">
            {icon}
          </div>
        )
     })
   }
}
Related