I'm still fairly new to using typescript but I encountered a situation I don't quite know how to solve. I'm trying to take some static json data I have in my react typescript project and use it as a semantic ui component variable value.
I have a file named socials.ts
saved in a data/
directory, and it looks like
export const socials = [
{
"id":1,
"media": "github"
...
...}
]
And then I have another component SocialsLinks.tsx
that is suppose to display the icons as a link for each value in the socials object.
...
import {socials } from "data/socials"
import { Icon } from "semantic-ui-react";
export const Socials = () => {
return (
<>
{socials.map((social) => (
<a
key={social.id}
href={`https://${social.media}.com/${social.username}`}
>
<Icon name={ social.media }/>
</a>
))}
</>
);
};
Obviously <Icon name={ social.media }/>
throws a type error since the string social.media has type any, and Icon only accepts defined semantic UI strings.
I was wondering if there was a way to cast the social.media string to be a semantic UI one? Or define types for the original json object so that it would work like this?
Try this approach,
I have created an interface
for the record.
import * as React from "react";
import "./styles.css";
import { Icon } from "semantic-ui-react";
import { SemanticICONS } from "semantic-ui-react/dist/commonjs/generic";
interface Social {
id: number;
username: string;
media: SemanticICONS;
}
export const App = () => {
const socials: Social[] = [
{
"id":1,
"media": 'github',
username: 'james'
}
]
return (
<>
{socials.map((social: Social) => (
<a
key={social.id}
href={`https://${social.media}.com/${social.username}`}
>
<Icon name={ social.media }/>
</a>
))}
</>
);
};
Hope this is what you are looking for.