I have a js file with an array of objects, I am trying to load the attributes dynamically with a component and I cannot seem to figure out how to pass icons to the rendering component.
Here is the component that I am using to render the data:
import React, { Component } from 'react'; import SkillData from '../../store/skillData'; import './SkillsCard.css'; class SkillsCard extends Component { state = { } renderSkills = () => SkillData.map((skill, _id) => <div key={_id} className="skillCard col-sm-3 m-2"> <div className="top"> {/* ***line in question*** */} <div className="icon">{skill.icon}</div> <h5>{skill.title}</h5> </div> <div className="bottom"> {skill.techs.map((tech,index)=>( <div className='skillCardList' key={index}> {tech}</div> ))} </div> </div> ); render() { return ( this.renderSkills() ); } } export default SkillsCard;
and here is the file that I am pulling data from:
const SkillData = [ { _id: '1', icon: '../../assets/icons/frontend.png', title: 'Front End', techs: ['HTML5', 'CSS | SCSS', 'JavaScript', 'React | Redux', 'Angular'] }, { _id: '2', icon: '../../assets/icons/server.png', title: 'Back End', techs: ['NodeJS', 'Express', 'Postman', 'Authentication | Authorization'] }, { _id: '3', icon: '../../assets/icons/database.png', title: 'Databases', techs: ['MongoDB', 'mySQL', 'PostgreSQL'] } ] export default SkillData
The issue that I am having is that I cannot get the path name to the icons to evaluate and actually render the icon; Instead my component renders the text, listed on the path. All the other attributes render just fine? Any thoughts?
Because you're just rendering the string value to the page:
<div className="icon">{skill.icon}</div>
Did you mean to use an <img>
element?:
<div className="icon">
<img src={skill.icon} />
</div>
This worked when I added
const icons = require.context('../assets/icons', true);
in the SKillData.js file and set the paths to:
icons('./iconName.png'),
Thanks a million, David!
This works for me.
Direct require from your local assets folder, so you dont need the complexity to head file import a link from a json file request
{/* line in question */}
<div className="icon">
<img src={require(`${skill.icon}`)} />
</div>
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.