React import json data - reactjs

I draw a graph by using react vega. When i write config for the graph it works. I would like to get config in json format from an external file
barChartConfig.json
I try to import this file but did not work. My question is how can i import a json and assign it into a variable?
import config from './barChartConfig.json';
const barSpec = config;
const Vega = ReactVega.default;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
spec: barSpec
// ,data: barData
};
}
render() {
return (
<div>
<Vega spec={this.state.spec} />
</div>
);
}
}
const app = document.getElementById('app');
ReactDOM.render(<App />, app);

When you use this:
import config from './barChartConfig.json'; it means you are "asking" your bundler (webpack?) to include the data of this file when it creates the bundle.js file.
Of course you will need an appropriate loader for that like json-loader.
If you are trying to get this data on run time then you will need to get it via ajax request. (fetch, axios etc...)

If you are using create-react-app, json-loader will be already included. In that case you can use the following statement to load json file.
var config = require('./barChartConfig.json');

Related

React D3 error 404 when importing a .csv file

I'm trying to use csv from d3 to render some data in my Next.js application. Following this tutorial, I got a 404 error. I've searched a lot, and as it's showed in the video, it's possible to use csv with React. Here is my code
import {csv} from 'd3';
import datacsv from './test.csv';
class Power extends Component {
...
componentDidMount() {
csv(datacsv).then(data=>{
console.log(data);
});
}
...
I've double-checked the path to the file.
Note.
I've seen some questions in StackOverflow about this topic but they refer to Node.js or are not answered.
d3.csv expects a URL to be passed, not a file path or module.
You can move the test.csv file to your public/ folder as to provide a valid location for d3.csv() to fetch the data from, then point to it.
import { csv } from 'd3';
class Power extends React.Component {
// ...
csv('/test.csv').then((data) => {
console.log(data);
});
// ...
}
Alternatively, if you want to read the .csv file from the file system in your Next.js app, you'll need to install csv-loader and add it to your next.config.js's webpack config.
$ npm install csv-loader
// next.config.json
module.exports = {
webpack: (config) => {
config.module.rules.push({
test: /\.csv$/,
loader: 'csv-loader',
options: {
dynamicTyping: true,
header: true,
skipEmptyLines: true
}
});
return config;
}
};
You can then load the test.csv file directly, without having to use d3.csv.
import datacsv from './test.csv';
class Power extends React.Component {
// ...
componentDidMount() {
console.log(datacsv);
}
// ...
}

ckeditor4 editorConfig and editorUrl is not working in react?

i have download full package of ckeditorckeditor_4.14.1_full.zip and extract in my assets folder but when i use this dir as CKEditor.editorUrl = '../assets/ckeditor/ckeditor.js'; then it's not working, if i use CDN like CKEditor.editorUrl = '//cdn.ckeditor.com/4.14.1/full/ckeditor.js'; then it's working fine and editorConfig is not working also...
would you like to tell me how can i define that?
createForm.js
import React, { Component } from 'react';
import CKEditor from 'ckeditor4-react';
CKEditor.editorUrl = '../assets/ckeditor/ckeditor.js'; // this link is not working...
//CKEditor.editorUrl = '//cdn.ckeditor.com/4.14.1/full/ckeditor.js'; it's working!
CKEditor.editorConfig = function (config) {
config.uiColor = '#2b2c26';
config.contentsCss = '../assets/desk/fonts/Nafees-Nastaleeq/css/font.css';
config.font_names = 'Nafees Nastaleeq;' + config.font_names;
};
class App extends Component {
render() {
return (
<div className="App">
<h2>Using CKEditor 4 in React</h2>
<CKEditor
data="<p>Hello from CKEditor 4!</p>"
/>
</div>
);
}
}
export default App;
Try to expose the ckeditor.js file from your server, and use the http url as
CKEditor.editorUrl = 'http://localhost:5000/ckeditor/ckeditor.js';
CKEditor.editorUrl = '../assets/ckeditor/ckeditor.js';
should be
CKEditor.editorUrl = '/assets/ckeditor/ckeditor.js';
if it is not work you could and your site url by using process.env
import CKEditor from 'ckeditor4-react'
CKEditor.editorUrl = `${process.env.REACT_APP_BASE_URL}/ckeditor/ckeditor.js`
you could set REACT_APP_BASE_URL for prod and development

Retrieving data from a local json file in react

How can i retrieve some data from a local json file i created in my folder? i´m using the following code:
class Intro2 extends Component {
render() {
async function getData() {
const usersData = await fetch("../articles.json");
const users = await usersData.json();
return users;
}
}
This doesn't seem to work for my local json file but if i use a url from git hub users for example its working?
many thanks
The error: main.chunk.js:332 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
You shouldn't be using fetch.
Use import instead. This will ensure webpack doesn't bundle the json file.
But makes it available in the public directory.
const usersData = await import("../articles.json");
Fetch will never work because webpack won't serve your JSON file.
Not unless you put it in a the static or public folder.
I think if you're trying to read from your file system you won't be able to do it, because in at least some browsers, you will need to serve the file via a web server process.
But if you are trying to read from http://localhost:9000/articles.json the issue could be another thing.
Maybe you need the {mode:'no-cors'} param ?
fetch('../static/test.txt', {mode: 'no-cors'})
Else you could simply export it:
export const json = () => ({...})
and then import it to your file:
import {json} from '../json
Assuming the json is in the project's folder structure.
import React from "react";
import ReactDom from "react-dom";
import usersData from "../articles.json";
class Intro2 extends React.Component {
state = {
usersData: { ...usersData },
};
componentDidMount() {
// a place for promises
};
render() {
// where the jsx is rendered
return <div>Renders JSX with state {this.state.usersData.aKey}</div>;
}
};
or with react functional components
// Alternatively, use functional components:
import React from "react";
import usersData from "../articles.json";
function Intro2() {
const [usersData, setUsersData] = React.useState({ ...usersData });
return <div>Renders JSX with state {usersData.aKey}</div>;
}

import file dynamically by variable - react native

I have a path.json file that contains the path of a component
// path.json
{
"main": "./login/index.js",
"paths": [
{
"name": "login",
"path": "./login/index.js",
"image": ""
}
]
}
I want to load './login/index.js' file dynamically in react native and render this particular file
My current implementation
const MyComponent = createLazyContainer(() => {
const componentPath = PathJson.main; // ./login/index.js
return import(`${componentPath}`); //import error here # line 7
});
export default MyComponent;
I am getting following error :
Invalid call at line 7: import("" + componentPath)
What people have been telling you in the thread is correct but I'd like to add one possible solution. All the imports/require are resolved at compilation time and not at running time which you are trying to do. By the time you are running your app, if you haven't imported the files, you can't use them.
There is a workaround tho, assuming that you know all the files that you might in advance which is to do something like a factory:
const possiblePaths = {
'one': require('path/to/file/1'),
'two': require('path/to/file/2')
}
function(type){
return possiblePaths[type];
}
And then you use it somehow like:
render(){
const MyComponent = function('one');
return <MyComponent/>;
}
This is more or less pseudo code and my not work right away, but hopefully yo get the idea. You need to store a reference to each of the imports you might need and then dont use the import, use the reference that was created for you at compilation time.
Actually, the React Native development concerns are not like development for the Web.
Just for this reason, it is not so important at all to have lazy loading in the production of a react-native project. Just import anything you want and then use them in any files of the project. all of them are in the bundle of production and exactly it is not important at all.
So for this problem, I prefer to have a helper file to collect all selectable libraries and export them:
// helper file
export { default as Index } from './Login';
export { default as OtherComponent } from './OtherComponent';
Then when you wanna use:
import { Index, OtherComponent } from 'helper';
~~~
render() {
const MyComponent = someCondition ? Index : OtherComponent;
return (
<MyComponent />;
);
}
Solution:
const allPaths = {
path1: require('file path1').default,
path2: require('file path2').default
};
render(){
const MyComponent = allPaths["path1"];
return <MyComponent/>
}
In React Native all the files that are being imported are bundled together, only those files can be dynamically imported.
Let's say you have three files index.js, test_1.js and test_2.js and if you have imported only test_1.js in index.js than React Native will only bundle those two files leaving test_2.js.
So to answer your question even if dynamic import works in React Native but because these files are not part of the bundle you are not able to import them.
I've once been in a similar situation where I need to do imports by variable, but that is limited to importing components inside a component and it uses code-splitting (Edit: I'm playing around to look for a solution without relying on code-splitting, I just realized there was a react-native tag in the question, and I don't think code-splitting is a good choice to go with in RN). I'm not sure by how much my method could help you, but here goes.
Side notes:
Importing folder that contains an index.js(jsx|ts|tsx) file should automatically resolve to that index file.
Importing from from './login/index.js' usually throws a 'Module not found' error. Either import from './login/index' or from './login but I prefer the last one as it's the shortest & simplest.
In path.json:
{
"main": "./login", // '.js' is removed
"paths": [
{
"name": "login",
"path": "./login/index.js", // Not sure what this is for, but if necessary, remove the '.js' here as well
"image": ""
}
]
}
In MyComponent.js:
import React, { lazy, Suspense } from 'react'
import PathJson from './path'
// 1. We need a UI to show while component is being loaded
const Loader = () => <div>{'Loading...'}</div>
// 2. We need a fallback UI if component is not found
const DocUnavailable = () => <div>{'We\'re sorry, but this document is unavailable.'}</div>
// 3. Create a resolver function ('resolver' is just a name I give)
function resolveImport(pathToComponent, FallbackComponent) {
let componentFound = false
let RenderComponent = () => <FallbackComponent /> // Assign fallback first
try {
if (require.resolve(pathToComponent)) {
componentFound = true
}
} catch (e) { } // Kinda hacky, if you don't mind, but it works
if (componentFound) {
// If found, replace fallback with the valid component
RenderComponent = lazy(() => import(pathToComponent))
}
return RenderComponent
}
// 4. Finally, implement it in a component
class MyComponent extends React.Component {
render() {
const componentPath = PathJson.main
const RenderComponent = resolveImport(componentPath, DocUnavailable)
return (
<Suspense fallback={<Loader />}>
<RenderComponent />
</Suspense>
)
}
}
export default MyComponent
References:
Implementation for 'resolver' function based on Langutil
Code-splitting with lazy & Suspense based on React Docs

SnapSVGAnimator.js generates errors when loading in React web app

SnapSVG extension for Adobe Animate.cc 2017 is able to create interactivity and animations for the web. I'm currently trying to use an exported SnapSVG Adobe Animate.cc project in my REACT JS WebApplication.
What I've done so far:
Imported snapsvg-cjs from npm( modified snapsvg to use succesfull in React)
Imported axios to load custom json file generated from SnapSVG extension in Animate.cc
Excluded minified code with eslintignore from SnapSVGAnimator. lib, generated while publishing SVG animation from Animate.cc to work properly without the ESlinting warnings.
Create a componentDidMount function
current code:
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { SVGAnim } from './SnapSVGAnimator.js';
import snapsvg from 'snapsvg-cjs';
componentDidMount(){
axios.get(jsonfile)
.then(response => {
const json = response.request.responseText;
const comp = new SVGAnim(json);
console.log(comp)
});
}
Problem
Following error appears while I log const comp.
Uncaught (in promise) TypeError:
_SnapSVGAnimator.SVGAnim is not a constructor
During the publish render in Animate.cc there are two libs generated; snapsvg.js and SVGAnimator.js
You can import snapsvg-cjs from NPM but SVGAnimator.js isn't available. Importing SVGAnimator.js with the ES6 approach from a curtain directory in your ReactApp isn't possible, not even by excluding it from linting with /* eslint-disable */ 1000 warnings still appears.
Instead of that, add the code to your index.html file, located in the public folder this way
(I've used create-react-app to build this project):
<script type="text/javascript" src="%PUBLIC_URL%/libs/SnapSVGAnimator.min.js"></script>
This is the working code:
import React, { Component } from 'react';
//axios for asnyc usage*/
import axios from 'axios';
//Snapsvg-cjs works out of the box with webpack
import Snapsvg from 'snapsvg-cjs';
//snap.json is located in the public folder, dev-build folder(ugly approach).
let jsonfile = "snap.json";
class SVGAnimator extends Component {
constructor(props){
super(props);
this.state = {
data: ''
}
}
componentDidMount(){
axios.get(jsonfile)
.then(response => {
this.setState({ data: response.data })
});
}
getSVG(){
if(this.state.data){
const container = document.getElementById('container');
const SVG = new window.SVGAnim(this.state.data, 269, 163, 24)
container.appendChild(SVG.s.node);
}
}
render() {
return (
<div id="container">
{ this.getSVG()}
</div>
);
}
}
export default SVGAnimator;

Resources