Reputation: 107
I have an array like this in React data file and I'm using the .map()
method to load JSON data in component ProjectItem.js
.
When I type {console.log("title" + projects[0].title)}
and log data Projecttitle1 appears on console. How should I take the data, render that data on my web-app itself in functional component? (Projecttitle1 to show on the web-app)
Data.json
{
"projects": [
{
"title": "Projecttitle1",
"category": "frontend development",
"description": "",
"desktop": [],
"mobile": []
}
]
}
ProjectItem.js
import React from 'react';
import './ProjectItem.scss';
import useWindowWidth from '../../Hooks/useWindowWidth.js';
import { projects } from '../../data'
import desktopImage from '../../Assets/Images/Projects/Desktop/123.jpg';
import mobileImage from '../../Assets/Images/Projects/Mobile/123_square.jpg'
const ProjectItem = ({ viewProject }) => {
const imageUrl = useWindowWidth() >= 650 ? desktopImage : mobileImage;
const { windowWidth } = useWindowWidth();
return(
<div className="projectItem" style={{ backgroundImage: `url(${ imageUrl })`}}>
{windowWidth >= 650 &&(
<>
<div className="title">
{projects.map((data, key)=>{
console.log(key);
return(
<div key={key}>
{data.title}
</div>
);
})}
</div>
<div className="viewProject">{viewProject}</div>
</>
)}
</div>
);
};
export default ProjectItem
Console:
I've tried some attemps to import json file and then deconstruct from parsed json. Now when I run npm the data still isn't printing on web-app. Would there be possible solution to this?
attempt1:
import data from '../../data'
const { projects } =() => JSON.parse(data)
attempt2:
import data from '../../data'
const {projects} =() => JSON.parse(JSON.stringify(data))
Upvotes: 0
Views: 1241
Reputation: 545
You are trying to deconstruct from json file which is basically a string representation of your object. you need to import it, and then deconstruct from a parsed json solution for this would be:
import data from '../../data'
const { windowWidth } = useWindowWidth();
const { projects } = JSON.parse(data)
return(
<div className="projectItem" style={{ backgroundImage: `url(${ imageUrl })`}}>
{windowWidth >= 650 &&(
<>
<div className="title">
{projects.map((data, key)=>{
console.log(key);
return(
<div key={key}>
{data.title}
</div>
);
})}
</div>
<div className="viewProject">{viewProject}</div>
</>
)}
</div>
);
Upvotes: 2