简体   繁体   中英

How to dynamically add react icons to an Object

I'm building an accordion for this website and im having trouble adding react icons to the title of each accordion title. I've used this approach below to dynamically add accordion tabs with the contents being those 3 components that are in the content object.

How would I even add a simple h2 tag to each accordion tab title dynamically

const content = {
  'Blogs': <Blogs />,
  'icon': <h2>hi</h2>,
  'Webinars': <Webinars />,
  'Podcast': <Podcasts />,
}

const AccordionSingle = (name) => {
  const [isOpen, setOpen] = useState(false);

  return (
    <div className="accordion-wrapper">
      <div
        className={`accordion-title ${isOpen ? "open" : ""}`}
        onClick={() => setOpen(!isOpen)}
      >
        {name}
      </div>
      <div className={`accordion-item ${!isOpen ? "collapsed" : ""}`}>
        <div className="accordion-content">{content[name]}</div>
      </div>
    </div>
  );
};

const Resources = (props) => {

  return (
    <>
      <Navbar />
      <div>
        {
          ['Webinars', 'Blogs', 'Podcast'].map(d => AccordionSingle(d))
        }
      </div>
    </>
  );
}

export default Resources;

if I got you correct, you want to add icons to all titles within your accordion (or any other text, h2 for example). From that point it is not clear why you are adding h2 to the items list. It should be added inside of your div containing title:

<div
  className={`accordion-title ${isOpen ? "open" : ""}`}
  onClick={() => setOpen(!isOpen)}
>
  <h2>text</h2>{name}
</div>

Also, I would recommend to store your items as an array because it is actually a list of items with own properties. It may look like this:

const items = [
  { 
    name: "Blogs",
    content: <Blogs />,
    icon: <FaPenFancy /> // it is just an example from react-icons
  },
  ...
]

This way you can later use the icon as a part of title instead of shown above.

This way it is better to update the code with sending the entire item object to AccordionSingle props:

// instead of:
{
  ['Webinars', 'Blogs', 'Podcast'].map(d => AccordionSingle(d))
}
// should be:
  items.map(d => AccordionSingle(d))

// and then extract all properties inside you AccordionSingle props:
const AccordionSingle = ({name, content, icon}) => {
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM