Reputation: 153
I have some paths in a react file that look like this:
import azureIcon from './azure.png';
import dropboxIcon from './dropbox.png';
I also have a separate JSON file that looks like this:
{
"posts": [
{
"id": 1,
"name": "azure",
"description": "blah blah",
"icon": "azureIcon"
},
{
"id": 2,
"name": "dropbox",
"description": "blah blah",
"icon": "dropboxIcon"
}
]
}
Is it possible to have it identify the variable like this? Or will it not work because currently the value of "icon" is set to a string value? What would be a good way to approach this?
Thank you!
Upvotes: 0
Views: 131
Reputation: 129
If I have to use icons as images I would choose the way @Kison suggests.But it is nice if you could font awesome, here it is showed how to install/import font awesome https://fontawesome.com/start and you can search icon here https://fontawesome.com/icons?d=gallery and all you have to do is paste the website says html code it is like following:
<i class="fab fa-accusoft"></i>
this will render azure icon and
<i class="fab fa-dropbox"></i>
this will render dropbox icon.
Here these are two icons' links:
(azure icon) https://fontawesome.com/icons/accusoft?style=brands
(dropbox icon) https://fontawesome.com/icons/dropbox?style=brands
Upvotes: 1
Reputation: 1084
I would suggest to place images in public accessible folder. Here is example from create-react-app docs section in case you use it.
So to simplify your code you can use such approach:
const posts = [
{
"id": 1,
"name": "azure",
"description": "blah blah",
"icon": "azure.png"
},
{
"id": 2,
"name": "dropbox",
"description": "blah blah",
"icon": "dropbox.png"
}
]
const Component = (posts) => (
<React.Fragment>
{posts.map(post => <img
key={post.id}
src={process.env.PUBLIC_URL + `/icons/${post.icon}`}
/>}
</React.Fragment>
)
Upvotes: 1
Reputation: 670
It is impossible to do this directly, but you could do something like
const icons = { azureIcon, dropboxIcon };
const MyComponent = () => {
return (
<div>
{posts.map(post => (
/*or w/e the correct way to normally render it is*/
<img src={icons[post.icon]} />
)}
</div>
)
}
Upvotes: 1