Import static JSON data in React - javascript

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

Related

Undefined after console are homepage to see if we getting correct the data in inspect element [Solved]

The detail of the problem is that I'm not getting the data we expected within our code. We have set up the following to see within our project folder.
Within webpack.config.js we set up resolve.alias in the webpack configuration, so we can include it in the resolve object of the webpack config file.
This is the file:
module.exports = {
// other webpack config options
resolve: {
alias: {
// Create an alias for the queries folder
queries: path.resolve(__dirname, 'src/queries'),
},
},
};
This is what are path name will look like:
import { homeQuery } from "queries/navigation/homeLinks";
Created a webpack.config.js.
Console.log are data of homeData and HomeData.homelink.
Tested the query within GraphQL Playground in Hygraph.
From there I checked the console in the browser.
I have found out we are not getting the query in our body that we want but we have tested the query within GraphQL Playground. We have found out that we correctly getting the correct query that we want to get into our data within console.log.
This is a query for the homepage:
import { gql } from "#apollo/client";
export const homeQuery = gql`
query homeLinks {
pages(
where: {id: "clbzl7ovpe64d0ak5qh7o2p8f", slug: "Home"}
stage: PUBLISHED
locales: en
) {
id
slug
title
}
}`
;
This where we console are data for the homepage:
console.log(homeData && homeData?.homeLink?.pages);
console.log(homeData)
import React from 'react';
import '../assets/style/navigation.css';
import { useQuery } from '#apollo/client';
import { BrowserRouter as Router, Link } from 'react-router-dom';
import { homeQuery } from "../queries/navigation/homeLinks";
import { logoassetsQuery } from "../queries/navigation/logoLinks";
export default function App() {
const { loading: logoAssetsLoading, error: logoassetsData } = useQuery(logoassetsQuery);
//This is query for the pages.
const { loading: homeLoading, error: homeError, data: homeData } = useQuery(homeQuery);
//This is for front-end error message.
if (logoAssetsLoading) return <p>Loading Logo Assets...</p>;
if (homeLoading) return <p>Loading... this page links.</p>
if (homeError) return <p>Error :( this page don't work.</p>;
// Debugging step 1: Check the value of data.navigation
console.log(homeData && homeData.homeLinks)
console.log(homeData)
// Debugging step 2: Check the value of data
//console.log(data);
return (
<div className='navigation'>
<div className='full_width_container'>
<div className='wrapper'>
<Router>
<React.Fragment>
<nav>
<div className='nav_groups logo'>
{homeData && homeData?.homeLinks?.pages && homeData?.homeLinks?.page(link => (
<li key={link?.id}>
<Link to={`/${link?.slug}`}>
<img src={logoassetsData?.logoAssets} alt='main logo'/>
</Link>
</li>
))}
</div>
</nav>
</React.Fragment>
</Router>
</div>
</div>
</div>
);
}

How to get array of objects in javascript from an array of dictionaries in python?

I'm trying to use an array of dictionaries in python as arguement to a custom dash component and use it as array of objects
in python :
audioList_py = [
{
"name": "random",
"singer": 'waveGAN\'s music',
"cover":
'link_1.jpg',
"musicSrc":
'link_1.mp3',
},
{
"name": "random",
"singer": 'waveGAN\'s music',
"cover":
'link_2.jpg',
"musicSrc":
'link_2.mp3',
},
... etc
]
in Javascript:
audioList1_js = [
{
name: "random",
singer: 'waveGAN\'s music',
cover:'link_1.jpg',
musicSrc: 'link_1.mp3',
},
{
name: "random",
singer: 'waveGAN\'s music',
cover: 'link_2.jpg',
musicSrc: 'link_2.mp3',
},
... etc
]
Here is snippet of javascript code of the dash custom component:
export default class MusicComponent extends Component {
render() {
const {id, audioLists} = this.props;
return (
<div>
<h1>{id}</h1>
<ReactJkMusicPlayer audioLists={audio_list}/>,
</div>
);
}
}
MusicComponent.defaultProps = {};
MusicComponent.propTypes = {
/**
* The ID used to identify this component in Dash callbacks.
*/
audios: PropTypes.array,
id: PropTypes.string,
};
And using the generated component in python:
app = dash.Dash(__name__)
app.layout = html.Div([
music_component.MusicComponent(audios=audioList_py),
html.Div(id='output'),
... etc
])
But I got :
TypeError: The `music_component.MusicComponent` component (version 0.0.1) received an unexpected keyword argument: `audios`Allowed arguments: id
What I am doing wrong ?
Any help or advice will be appreciated, Thanks a lot.
Make sure you run npm run build after you make a change to your custom React component. With those proptypes you shouldn't get that error. If I remove the audios proptype I can reproduce that error.
Besides that you pass a value to the audios property:
music_component.MusicComponent(audios=audioList_py)
but you try to retrieve audioLists from props:
const {id, audioLists} = this.props;
Change this to:
const {id, audios} = this.props;
Demo
export default class MusicComponent extends Component {
render() {
const {id, audios} = this.props;
return (
<div>
<h1>{id}</h1>
<ReactJkMusicPlayer audioLists={audios} />
</div>
);
}
}
MusicComponent.defaultProps = {};
MusicComponent.propTypes = {
/**
* The ID used to identify this component in Dash callbacks.
*/
id: PropTypes.string,
audios: PropTypes.array,
};
Issue fixed, I should run : npm run build:backends to generate the Python, R and Julia class files for the components, but instead I was executing npm run build:js and this command just generate the JavaScript bundle (which didn't know about the new props).
And set the audios property in the component to be like so:
MusicComponent.defaultProps = {audios: audioList1};
MusicComponent.propTypes = {
id: PropTypes.string,
audios: PropTypes.arrayOf(PropTypes.objectOf(PropTypes.string)).isRequired
};

React-Image-Annotate - SyntaxError: Cannot use import statement outside a module

I'm trying to use react-image-annotate but it's giving me this issue when I first try to set it up.
And here's how I'm using it:
import React from 'react'
import ReactImageAnnotate from 'react-image-annotate'
function ImageAnnotator() {
return (
<ReactImageAnnotate
selectedImage="https://images.unsplash.com/photo-1561518776-e76a5e48f731?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
// taskDescription="# Draw region around each face\n\nInclude chin and hair."
// images={[
// { src: 'https://example.com/image1.png', name: 'Image 1' },
// ]}
// regionClsList={['Man Face', 'Woman Face']}
/>
)
}
export default ImageAnnotator
I'm using Next.js if that matters
UPDATE 1
I tried using this babel plugin as suggested by Alejandro Vales. It gives the same error as before. Here's the babel key in my package.json:
"babel": {
"presets": [
"next/babel"
],
"plugins": [
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-transform-modules-commonjs",
{
"allowTopLevelThis": true
}
]
]
}
I would say that the issue relies in the library itself by what they replied in here (similar bug) https://github.com/UniversalDataTool/react-image-annotate/issues/90#issuecomment-683221311
Indeed one way to fix it I would say is adding babel to the project so you can transform the imports in your project to require automatically without having to change the code on your whole project.
This is the babel package you are looking for https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs
Another reason for this could be an outdated version of your package, as some people report to have this fixed after using a newer version of Create React App (https://github.com/UniversalDataTool/react-image-annotate/issues/37#issuecomment-607372287)
Another fix you could do (a little crazier depending on your resources) is forking the library, creating a CJS version of the lib, and then pushing that to the library, so you and anybody else can use that in the future.
I got a tricky solution!
Problem is that react-image-annotate can only be imported in client-side(SSR got error for import keyword)
So, let react-image-annotate in Nextjs be imported only in client side
(https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr)
in Next Page that needs this component, You can make component like this
import dynamic from "next/dynamic";
const DynamicComponentWithNoSSR = dynamic(() => import("src/components/Upload/Annotation"), { ssr: false });
import { NextPage } from "next";
const Page: NextPage = () => {
return (
<>
<DynamicComponentWithNoSSR />
</>
);
};
export default Page;
Make component like this
//#ts-ignore
import ReactImageAnnotate from "react-image-annotate";
import React from "react";
const Annotation = () => {
return (
<ReactImageAnnotate
labelImages
regionClsList={["Alpha", "Beta", "Charlie", "Delta"]}
regionTagList={["tag1", "tag2", "tag3"]}
images={[
{
src: "https://placekitten.com/408/287",
name: "Image 1",
regions: [],
},
]}
/>
);
};
export default Annotation;

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

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

Categories