Reputation: 113
How to render component based on json file information? I have a map that is rendering a UL list. Each Li is rendered. (I know i can do this with a img and than passing src={} as a object from the json file. But i wanna know if there's another way of solving this. Code below:
import React from 'react'
import { FiLinkedin as LinkedinIcon, FiGithub as GithubIcon } from 'react-icons/fi';
import Data from '../../socials.json';
import { Container } from './styles';
export default function Profile() {
return (
<Container>
<ul id="profile-links">
{Data.map((social, index) => {
return (
<li id={social.id} key={social.id}>
<a href={social.url} target="_BLANK" rel="noreferrer">
<LinkedinIcon size={22} /> // change this component based on -social.icon info-
<strong>{social.title}</strong>
<span className="small-link">{social.slug}</span>
</a>
</li>
)
})}
</ul>
</Container>
)
}
Upvotes: 0
Views: 1272
Reputation: 5064
You can create a method which will give you the icon depending on the social.icon
value. For example:
const getIcon = (icon) => {
switch(icon) {
case A:
return <IconA />;
case B:
return <IconB />;
default:
return null;
}
}
And call this getIcon method where you need it with the social.icon
as params.
Upvotes: 1
Reputation: 15462
I would convert your socials.json
into a socials.js
. Then you can set up your data more flexibly like this:
import {
FiLinkedin as LinkedinIcon,
FiGithub as GithubIcon,
} from 'react-icons/fi';
const Data = [
{
id: 1,
url: 'url 1',
title: 'title 1',
slug: 'slug 1',
icon: LinkedinIcon,
},
// Other socials...
];
export default Data;
Then you can render these icons dynamically in your map like this:
// ...
import Data from '../../socials';
export default function Profile() {
return (
<Container>
<ul id="profile-links">
{Data.map((social, index) => {
return (
<li id={social.id} key={social.id}>
<a href={social.url} target="_BLANK" rel="noreferrer">
<social.icon size={20} />
<strong>{social.title}</strong>
<span className="small-link">{social.slug}</span>
</a>
</li>
);
})}
</ul>
</Container>
);
}
Upvotes: 2