React D3 error 404 when importing a .csv file - reactjs

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);
}
// ...
}

Related

How to import SVG in ReactJS with craco?

I'm struggling to import SVG's when I'm using craco in my react app.
It's suggested to use #svgr/webpack but I'm not sure how to put it into my craco.config.js
My current setup as per this (I prob shouldn't follow someone's config that doesn't work and expect it to work tho) that does not work:
// craco.config.js
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
baseUrl: "./src",
tsConfigPath: "./tsconfig.paths.json"
}
},
],
webpack: {
configure: (config, { env, paths }) => {
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
return config;
}
}
};
The craco.config.js webpack documentation is here but it's so confusing to me without concrete examples.
Also to note:
Writing import {ReactComponent as mySvg} from "./mySvg.svg" doesn't work because it doesn't recognize it as a ReactComponent.
If I try importing directly via import mySvg from "./mySvg.svg" Typescript doesn't recognize the file.
What I'm currently doing is putting the svg into a React component and using that but it's a nightmare doing that every time. I also put this in #types/custom.d.ts, but it still doesn't work when put into <img src={mySvg} />
// #types/custom.d.ts
declare module "*.svg" {
const content: any;
export default content;
}
import {reactComponent as GoogleLogo} from "../assets/image/googlelogo.svg;
GoogleLogo is component and reactComponent is a required magic string
i find the fix your problem in Adding svgr to create-react-app via craco

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>;
}

react-script: Transpiling Third party JSX files

I am developing application using create-react-app, and using third party module which is not compile, I am including JSX file from this to my project.
getting following error when start or build
******.jsx
Module parse failed: Unexpected token (12:25)
You may need an appropriate loader to handle this file type.
My react application is not eject and don't want to eject.
I don't want to eject from react-script
Sample code
Link.jsx in Library
import React from 'react';
import { string } from 'prop-types';
import './Link.scss';
const STATUS = {
HOVERED: 'hovered',
NORMAL: 'normal',
};
class Link extends React.Component {
constructor(props) {
super(props);
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
this.state = {
className: STATUS.NORMAL,
};
}
onMouseEnter() {
this.setState({ className: STATUS.HOVERED });
}
onMouseLeave() {
this.setState({ className: STATUS.NORMAL });
}
render() {
const { className } = this.state;
const { page, children } = this.props;
return (
<a
className={className}
href={page}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
>
{children}
</a>
);
}
}
Link.propTypes = {
page: string,
children: string,
};
Link.defaultProps = {
page: '#',
children: '',
};
export default Link;
Above code is publish to internal npm repo and used in application
App.jsx in application
import { Link} from '#myScope/myreactlib/Link'; // loaded from node_modules
App.jsx give error
When using create-react-app without ejecting, you will have some restrictions on how you can import modules.
If it is a custom module that you have built, then it needs to be in your src folder, and you import it using a path relative to your current file's path. For example: import MyComponent from './components/MyComponent
If it comes from a third-party dependency package (for example, reactstrap or #blueprintjs/core) which you have already added with npm or yarn, then you import it simply by specifying the package name. For example: import { Button } from 'reactstrap'
In your case, it sounds like you have a sub-folder in your node_modules folder which is for a package that you did not add with npm or yarn. While I doubt that it's recommended to use third-party packages this way, I'll assume that you have a good reason for doing so.
Without being able to see your entire setup, I would propose you try the following workaround:
In your src folder, create a symlink to the folder with your third-party package. For example (while in your project's src folder):
ln -s ../node_modules/#myScope/myreactlib myreactlib
Then, in your App.jsx file, do:
import { Link } from './myreactlib/Link'
Additional Information:
StackOverflow: The create-react-app imports restriction outside of src directory
StackOverflow: Import module from node_modules (create-react-app)
create-react-app documentation on importing a component

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;

React import json data

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');

Resources