So this is the JSON file with 3 objects
export const Projects = [
{
id: 1,
name: 'Site 1',
tech: [
'HTML',
'CSS',
'SASS',
'React'
],
description: 'Lorem1',
image: '/Image4.jpg'
},
{
id: 1,
name: 'Site 2',
tech: [
'HTML',
'CSS',
'SASS',
'React'
],
description: 'Lorem2',
image: '/Image4.jpg'
},
{
id: 1,
name: 'Site 3',
tech: [
'HTML',
'CSS',
'SASS',
'React'
],
description: 'Lorem3',
image: '/Image4.jpg'
}
];
I am trying to loop through the 'tech' arrays and return each item on its own. When I loop through them, right now I only get the full array and I can only put them all into a single div. This is how currently I do it and it works fine with the other parts, however, how can I receive the "tech" part with individual objects, rather than just the one array?
const Portfolio = () => {
const portfolioItem = Projects.map((project, i) => {
return <Item
key={i}
image={Projects[i].image}
description={Projects[i].description}
name={Projects[i].name}
tech={Projects[i].tech}
/>
})
You can use Array.flatMap()
to iterate the projects, with an internal Array.map()
to iterate the tech.
Note: The project.id
should be unique and used with the tech
as the key for the item.
const Portfolio = () => {
const portfolioItem = Projects.flatMap(project =>
project.tech.map(tech => (
<Item
key={`${project.id}-${tech}`}
image={project.image}
description={project.description}
name={project.name}
tech={tech}
/>
)
Assuming that rendering of tech
prop is implemented in a simple way, like this:
const Item = ({tech}) => <div>{tech}</div>
Then you can map the array of strings into an array of React elements:
<Item
key={i}
image={Projects[i].image}
description={Projects[i].description}
name={Projects[i].name}
tech={Projects[i].tech.map((t) => <span>{t}</span>)}
/>
Alternatively, you can convert the array to a single string, with explicit separator:
tech={Projects[i].tech.join(', ')}
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.