How can I put a JSON object into JSX? - javascript

I have a json array that contains some information :
[
{
"id": 1,
"imageUrl": "./img1.png",
},
{
"id": 2,
"imageUrl": "./img2.png",
}
]
I tried to make a class in which the elements were sorted and added the necessary link to the src, but the information from JSON is not put into JSX.
class Paintings extends Component {
render(){
return(
<ul>
{
paintings.map((s) => {
return (
<div>
<img src={s.imageUrl} alt={s.id} />
</div>
)
})
}
</ul>
)

The question is more general then just about images here. It is to import and loop a JSON object in JSX.
You have some syntax error in your code, I fixed them and shared an online editor implementation for you to have a look as well.
Save your json in a file and import that file in your react code then map the json object.
For the images location, although this is not the recommended method, I think you should put your images under public folder and make sure you have your json file with the correct path.
Sample JSON file I have structured, for your reference:
[
{
"id": 1,
"imageUrl": "image1.png"
},
{
"id": 2,
"imageUrl": "image2.png"
}
]
Then you should be able to use below code to be able to generate it.
import React, { Component } from "react";
import Painting from "./Painting";
class Paintings extends Component {
render() {
return (
<ul>
{Painting.map(({ id, imageUrl }) => (
<div key={id}>
<img src={imageUrl} alt={id} />
</div>
))}
</ul>
);
}
}
export default Paintings;
Here is a basic implementation for you to check out, we are able to map and see the items. I have added some sample images and please pay attention to json file and how its ready to map the JSX image objects based on the file paths.
https://codesandbox.io/s/react-json-into-jsx-19gj1w

Related

I can't export the array I have created in one of my react components

I have been trying to export this array to dynamically render on another page (based on input from fakeApi) within my app and can't get it to work. I'm new to react and not sure if this is the correct way to achieve what I want.
Basically, I would like the full api (yet to create just using fake one for testing) to appear on one page (which is working). Then based on the information received from the array show which networks are down on the homepage of my app. Any help is much appreciated. Please see code.
import NetworkComponent from './NetworkComponent';
let fakeApi = [
{
key: 1,
HostIPAddress: "1.1.1.1",
HostFriendlyName: "BBC",
HostMonitored: "down",
HostType: "VPN"
},
{
key: 2,
HostIPAddress: "8.8.8.8",
HostFriendlyName: "johnlewis.co.uk",
HostMonitored: "ok",
HostType: "VPN"
},
{
key: 3,
HostIPAddress: "2.3.4.5",
HostFriendlyName: "hello.co.uk",
HostMonitored: "down",
HostType: "VPN"
},
];
const NetworkScan = () => {
return (
<div>
<h1>Network Monitor</h1>
<div className="container mx-auto">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
{fakeApi.map(service => (
<NetworkComponent key={service.key} service={service} />
))}
</div>
{fakeApi.forEach((service) => {
if(service.HostMonitored === "down") {
let networkErr = [];
networkErr.push(service.HostMonitored, service.HostFriendlyName, service.HostIPAddress)
console.log(networkErr);
}
})};
</div>
</div>
);
};
export default NetworkScan;
You can export it as object export { fakeApi } and import it as import { fakeApi } from '../..'
Put that array object into a .json file (i.e. fakeApi.json) and import it like import fakeApi from './fakeApi.json' wherever you want.

broken logo image when importing from json file in React App

I am in the process of importing an svg image which path is in a json file. Below is part of the json file:
[
{
"id": 1,
"company": "Photosnap",
"logo": "./images/photosnap.svg",
"new": true,
"featured": true,
"position": "Senior Frontend Developer",
"role": "Frontend",
"level": "Senior",
"postedAt": "1d ago",
"contract": "Full Time",
"location": "USA Only",
"languages": ["HTML", "CSS", "JavaScript"]
},
{
I have created two components. As the app is showing a list of jobs. So the I have a job list component and a job card component.
The code for the job listing component is as follows:
import React from 'react';
import './job-listing.styles.css';
import JobCard from '../job-card/job-card.component.jsx/job-card.component';
import { Component } from 'react';
class JobListing extends Component {
constructor() {
super();
this.state = {
jobs: []
}
};
componentDidMount() {
fetch('/data.json')
.then(response => response.json())
.then(data => this.setState({jobs: data}))
}
render() {
return (
<div>
{this.state.jobs.map(({id, ...otherJobProps}) =>(
<JobCard key={id} {...otherJobProps} />
))}
</div>
)
}
}
export default JobListing;
and for the Job Card component is below:
import React from 'react';
import './job-card.styles.css';
const JobCard = ({company, position, postedAt, contract, location, logo }) => (
<div className='card'>
<img src={logo} alt="logo" width="42" height="42"></img>
<h2>{company}</h2>
<h1>{position}</h1>
<div className='details'>
<h3>{postedAt} ·</h3>
<h3>{contract} ·</h3>
<h3>{location}</h3>
</div>
</div>
)
export default JobCard;
At the moment this is what I get
Any help would be appreciated.
If you are using create-react-app you will want to put static assets such as images (if you are not not ES6 importing images into the code) in the public folder. Try moving these images into the public folder created by create-react-app. You may also need to update the paths. Assuming your structure is:
public
images
photosnap.svg
You may need to change:
"logo": "./images/photosnap.svg",
to:
"logo": "/images/photosnap.svg",
Hopefully that helps!

How to access Object array file into react component?

I am trying to access an object array file within src folder eg: data.js(Object array only) this file into my app.js(react component)
in first scenario 1.I have tried this problem using react in
src--[app.js(component)/data.js(object array)].
When I was run it shows me an error like
(TypeError: _data__WEBPACK_IMPORTED_MODULE_1___default.a.map is not a function)means null array/undefined.
in second scenarios 2. when I add object array in app.js within the same page its shows me perfect result. without an error but trying from another file like data.js it taking null array I have used to stringify() and JSON parser but no result
Object array file data.js ->
const datas=[
{
"id":"1",
"firstname":"sam",
"lastname":"parkar"
},
{
"id":"2",
"firstname":"julee",
"lastname":"fransic"
}
];
react component app.js ->
import React from 'react';
import datas from './data';
import DataInfo from './DataInfo';
function App () {
const appdata=datas.map( inner => inner.id + inner.firstname + inner.lastname)
//print on console
console.log(appdata)
return (
<div className="App">
<p>App js page</p>
{appdata}
</div>
)
}
export default App;
error ->
TypeError: _data__WEBPACK_IMPORTED_MODULE_1___default.a.map is not a function
21 | return (
22 |
23 |
> 24 | <div className="App">
| ^ 25 |
26 | <p>App js page</p>
actual result:-
App js page
1samparkar2juleefransic
and on console
(2) ["1samparkar", "2juleefransic"]
0: "1samparkar"
1: "2juleefransic"
Make sure you export the datas correctly
export const datas=[
{
"id": "1",
"firstname": "sam",
"lastname": "parkar"
},
{
"id": "2",
"firstname": "julee",
"lastname": "fransic"
}
];
And in app.js call it like this:
import {datas} from './data';
You can use JSON file like this:
datas.json
[
{
"id":"1",
"firstname":"sam",
"lastname":"parkar"
},
{
"id":"2",
"firstname":"julee",
"lastname":"fransic"
}
]
In app.js:
import datas from './datas.json';
If you are using JSON file then save that file as datas.json
Now in your app.js file use <datas/> instead of {datas}.
you can use {datas} when you are using it in a jsx attribute. for example-
<textarea name="JSON" value={datas} />.
but in your case, you should use <datas />.

Import static JSON data in React

I am trying to load static JSON data to my react app. But, it wan't allow me to load data.
I am using webpack version 4.26.1
It shows me following error:
SyntaxError: src/data/movieData.json: Unexpected token, expected ; (2:10)
1 | {
2 | "data": [
| ^
3 | {
4 | "id": 1,
5 | "title": "Freed",
My Code:
data/jsonResponse.json
{
"data": [
{
"id": 1,
"title": "Freed"
},
{
"id": 2,
"title": "Fifty"
}
]
}
main.js
import React, { Component } from 'react';
import Content from './Content';
import jsonResponse from './data/jsonResponse.json';
class Main extends Component {
render() {
return (
<div className="main">
<Content item={ jsonResponse } />
</div>
);
}
}
export default Main;
Content.js
import React from 'react';
const Content = () => {
const movies = this.props.item.data;
return (
movies.map(movie => {
return (
<span >{movie.title}</span>
);
})
)
}
export default Content;
Edited:
If i use js instead of JSON like:
const movies_data = {
"data": [
{
"id": 1,
"title": "Freed"
},
{
"id": 2,
"title": "Fifty"
}
]
}
export default movies_data;
and in Main.js file
import jsonResponse from './data/movieData';
Then in browser it shows following error.
Cannot read property 'props' of undefined
There are 2 workarounds for loading json files in a js file.
Rename your json file to .js extension and export default your json from there.
Since json-loader is loaded by default on webpack >= v2.0.0 there's no need to change your webpack configs.
But you need to load your json file as json!./data/jsonResponse.json (pay attention to json!)
EDIT:
Cannot read property 'props' of undefined
The reason you're getting this error is because you're trying to access this on a functional component!
Answer regarding edited question and Cannot read property 'props' of undefined error
You can't access this in functional components. props are passed as argument to functional components so please try this (Content.js file):
import React from 'react';
const Content = (props) => {
const movies = props.item.data;
return (
movies.map(movie => {
return (
<span >{movie.title}</span>
);
})
)
}
export default Content;
You have to add a JSON loader to import json files.
You need to check if in your Webpack config if exist an loader to JSON.
I recommend to use this loader.
https://www.npmjs.com/package/json-loader

React render gif files from JSON

I have data from a local JSON file. Each record has some text (string) and a map saved as .gif. The gif files I put in a folder inside ./src.
I need to reference the right map (gif file) to the right record.
Structure of JSON data file:
[
{
"id": "someid",
"text": "some text",
"map": "map name"
},
...
]
I have a component like this:
const Story = ({obj}) => (
<Card className="item" id={obj.id}>
{
obj.map
? (<div className="card-img-none"></div>)
: (<div className="card-img"></div>)
}
<CardBody>
<CardTitle>{obj.text}</CardTitle>
{
obj.map
? (<div className={obj.map}></div>)
: null
}
</CardBody>
</Card>
)
And render the Story component:
import data from './data.json';
...
<div>
{
this.state.data
? (
this.state.data.map((i) => (
<Story obj={i} key={i.id}/>
))
)
: ('Data not found')
}
</div>
Since the maps are gif, I've tried these:
import each gif and set if then statement to check if object.map == gif file name and render the gif file as <img src={mapName}/>, set css img {width: 100%}. This works only for one record since others have map key-value pair.
create a class in index.css for each map (e.g .mapName {background: url('./gif-file.gif') center no-repeat; background-size: cover; Then render the map like the code above. It works for all of them.
However, I run into the issue that I have to set the width and height of the map div to fixed value, setting width: 100% or height: 100% doesn't work. The values turn 0.
It seems like there must be a better solution for this. Any idea?
In case you have the same issue, I've figured out a workaround (it works but I'm not sure it's the best practice):
import data from './data.json'; // Import data from json file
import map from '<relative path>/map.gif'; // Import gif file with relative path
// Inside the class
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount = () => {
data[3].map = map; // Add value to key 'map' of the target element in data array
this.setState({data});
}
Hope this helps.

Categories