Search code examples
reactjsfont-awesomereact-bootstrapcardreact-icons

show reactjs icons dynamically icon names picking from JSON file


I'm having following json file, which I keep Id,Intro, Icon name

[
    {
        "id" : 7,
        "intro": "intro_7",
        "icon" : "ArrowRight"
       
    },
    {
        "id" : 8,
        "intro": "intro_8",
        "icon" : "Alarm"
    }
]

I'm using React-Bootstrap-Icons in my reusable card component as following

import "./bootstrap.min.css";
import * as Icon from './react-bootstrap-icons';

const Card = props =>{
    return(
     <div className="card text-center">
         <div className="card-body text-dark">
         
           <Icon.Alarm></Icon.Alarm>
            <h4 className="card-title">
                {props.intro}
            </h4>
         </div>
     </div>
    )
}

export default Card;

this is how I looping the json file and show cards

import Card from './card';
import CardData from './data.json';

class Cards extends Component {
    render() { 
      return ( 
      <div className="container-fluid d-flex justify-content-center">
          <div className="row">
              {
                CardData.map(({ id, icon, intro }, index) => (
                  <div key={title + index}>
                    <Card 
                    id={id} 
                    icon={icon} 
                    intro={intro} 
                   />
                  </div>
                  )
                )
              }
          </div>
      </div> 
      );
    }
  }
 
export default Cards;

but I want to take this to next level which is to show the Icons dynamically, that taking from json file, currently, it's static.

so I just try to put it like this

import React from 'react';
import "./bootstrap.min.css";
import * as Icon from './react-bootstrap-icons';   


const Card = props =>{
    return(
     <div className="card text-center">
         <div className="card-body text-dark">
         
           <Icon.+{props.icon}></Icon.+{props.icon}>
            <h4 className="card-title">
                {props.intro}
            </h4>
         </div>
     </div>
    )
}

export default Card;

but it's showing compilation errors in the first place. may I know is there any approach to achieve this


Solution

  • you are importing an object of icons. you can destructure your Icon first from icons based on props.icon, then call it:

    import * as Icons from 'react-bootstrap-icons';
    
    const Card = props =>{
      const { [props.icon]: Icon } = Icons
        return(
         <div className="card text-center">
             <div className="card-body text-dark">
             
               <Icon></Icon>
                <h4 className="card-title">
                    {props.intro}
                </h4>
             </div>
         </div>
        )
    }