reactjsfetchiconsreact-icons

React: How to display react-icons element using fetch API?


I stored my social links data on firebase, and now I want to make a <li> list of my social links but the icon object I have here, is not showing me the icons instead it's showing me the elements like: <BsBehance />. It should be displayed as icon, how can I do that?

Firebase data:-

enter image description here

Code:-

import { useEffect, useState } from "react";
import * as ReactIcons from "react-icons/fa";
import MainWrapper from "./MainWrapper";
import classes from "./pages.module.css";

export default function Footer() {
    const [socialLinks, setSocialLinks] = useState([]);

    useEffect(() => {
        const fetchSocilLinks = async () => {
            const res = await fetch(
                "https://mohitdevelops-d64e5-default-rtdb.asia-southeast1.firebasedatabase.app/accounts.json"
            );
            const data = await res.json();
            let loadedData = [];
            for (const keys in data) {
                loadedData.push({
                    url: data[keys].url,
                    icon: data[keys].icon,
                    id: data[keys].id,
                });
            }
            setSocialLinks(loadedData);
        };
        fetchSocilLinks().catch((err) => {
            console.log(err.message);
        });
    }, [socialLinks]);

    console.log(socialLinks);

    return (
        <footer className={classes.footer__wrap}>
            <MainWrapper>
                <p>Connect with me:</p>
                <ul className={classes.social_links}>
                    {socialLinks?.map(({ icon, id, url }) => {
                        const iconLink = icon.split(/\<|\/>/).filter((e) => e)[0];
                        const IconsComponent = ReactIcons[iconLink];
                        return (
                            <li key={id}>
                                <a href={url} target="_blank">
                                    <IconsComponent />
                                </a>
                            </li>
                        );
                    })}
                </ul>                   
            </MainWrapper>
        </footer>
    );
}

And its showing me like this:-

enter image description here

Everything data is coming fine, just need to know how to display an element which is working like an icon.


Solution

  • Since el.icon is a string, it's being displayed as a string. If you want to render the component based on that dynamic string, you need to have an object, where the key name is the string you will get from the server. And the value, can be the component itself.

    When you insert a string inside {}, React will render it as a string, even if they're in the < /> format.

    And also, try to never use dangerouslySetInnerHTML, since it has high security issues.

    Here is a codesanbox, for your above case. Please check this: