How to access Object array file into react component? - javascript

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 />.

Related

How can I put a JSON object into JSX?

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

Trying to display random data from a local json file I created, but getting an undefined error in render

I am learning React and right now I am trying to get my app to display a random joke (both question and answer) from the JSON file I created. However, I get the following error: getRandomJoke is not defined. I figured since it's a function, getRandomJoke does not need to get defined. Can someone explain where my mistake is and why I am getting this error?
This is the local JSON file I created:
SportsJokesData.js
const SportsJokesData = [
{
id: "1",
question: "What did the baseball glove say to the ball?",
answer: "Catch ya later!"
},
{
id: "2",
question: "What are the rules for zebra baseball?",
answer: "Three stripes and you’re out."
},
{
id: "3",
question: "Why are umpires always overweight?",
answer: "It’s their job to clean their plates."
}
export default SportsJokesData;
This is the component I created to get it displayed on my browser, SportsJokesApi.JS:
import React from 'react'
import SportsJokesData from './SportsJokesData';
class SportsJokesApi extends React.Component {
getRandomJoke(){
return SportsJokesData[(SportsJokesData.length * Math.random()) << 0]
}
render() {
return (
<p>{getRandomJoke}</p>
)
}
}
export default SportsJokesApi;
Do <p>{this.getRandomJoke()}</p> inside your render()

Can't import JSON in react

I'm having what I'm sure it's a stupid problem but I can't seem to find a way around it.
I have a react application and I'm trying to import a JSON file. Here it is:
{
"words":{
"ita":[
"ora",
"via",
"dio",
"sud",
"don",
"zia"
]
}
}
And here's the react code:
import React, { Component} from 'react'
import words from 'Assets/Words.json'
console.log(words)
console.log(words.ita)
export default class WordsGen extends Component {
...
The two console.log print, respectively:
{words: {…}}
words:
ita: (6) ["ora", "via", "dio", "sud", "don", "zia"]
__proto__: Object
__proto__: Object
and undefined.
I'm using the json file to put more languages in the app, but I can't understand why when I print just words I can see the property ita inside, and when I try to print words.ita or words["ita"] I get undefined.
What am I missing?
Should be:
words.words.ita
You are importing as "words" and then the object has a words object. It might be more clear to change the import name:
import MyJson from 'my.json';
console.log(MyJson.words.ita)
Because your imported object words contains whole json. When you write
import words from 'Assets/Words.json';
it will become
words = {
words:{
ita:[
"ora",
"via",
"dio",
"sud",
"don",
"zia"
]
}
}
That's why your object words doesn't really have property ita. That's why it will return undefined.
You need to write words.words.ita. For better code-style:
/// words.json
{
"ita":[
"ora",
"via",
"dio",
"sud",
"don",
"zia"
]
}
import words from 'Assets/Words.json';
words.ita // then your code
/// or even better with new es6 destructing
import {ita = []} from 'Assets/Words.json';
ita // do anything that you want

Query Strings with React for a small weather app

I want to be able to set a city for my weather app using query-strings like ?latt_long=34.052235,-118.243683&&woeid=2442047. Here is a link to it https://github.com/rushingMarina/weather-react-app . Right now I have a cities.json file in my project and App.js fetches data about the cities from there. I can not seem to figure out how to use query-strings. On https://www.npmjs.com/package/query-string it tells me to use const queryString = require('query-string'); in order to use query-strings but I can not declare a const in my App.js.
My App.js:
import React, { Component } from "react";
import FrontSide from "./FrontSide";
import BackSide from "./BackSide";
import "./panel.css";
import cities from "./cities.json"
import queryString from 'query-string';
class App extends Component {
const queryString = require('query-string'); //I get unexpected token error (11:6) on this line right before queryString
console.log(location.search);
state = {flipped: false, currentCity: cities[0]};
onFlip =() => {
this.setState({flipped: !this.state.flipped});
};
onSelectCity = (city) => {
this.setState({currentCity: city})
}
render() {
return (
<div className={`panel ${this.state.flipped ? 'flip' : ""}`}>
<div className="panel-front">
<FrontSide onClick={this.onFlip} currentCity={this.state.currentCity}/>
</div>
<div className="panel-back">
<BackSide
cities={cities}
onClick={this.onFlip}
currentCity={this.state.currentCity}
onSelect={this.onSelectCity}
/>
</div>
</div>
);
}
}
export default App;
My cities.json
[
{
"title":"Los Angeles",
"location_type":"City",
"woeid":2442047,
"latt_long":"34.052235,-118.243683"
},
{
"title":"San Diego",
"location_type":"City",
"woeid":2487889,
"latt_long":"32.715736,-117.161087"
},
{
"title":"New York",
"location_type":"City",
"woeid":2459115,
"latt_long":"40.730610,-73.935242"
},
{
"title":"Chicago",
"location_type":"City",
"woeid":2459115,
"latt_long":"41.881832,-87.623177"
},
{"title":"St Petersburg",
"location_type":"City",
"woeid":2123260,
"latt_long":"59.932739,30.306721"
}
]
i tried declaring
const queryString = require('query-string');
but react shows unexpected token at "queryString"
Please refer to my github link, there you will find App.js and cities.json files
I expect to get information about the city to display on my FrontSide from URL query-string like.
This is the error I am getting:
Failed to compile.
./src/App.js
Syntax error: Unexpected token (11:6)
9 | class App extends Component {
10 |
> 11 | const queryString = require('query-string');
| ^
12 | console.log(location.search);
13 |
14 | state = {flipped: false, currentCity: cities[0]};
Just remote the const queryString = require('query-string'); line out of the class declaration and put it on top. Just right below the import statements and everything should work fine. React doesn't like require statements inside the class declaration

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

Categories