VTK.js, React, JavaScript: Load VTK files - javascript

I have followed the introduction guide: https://kitware.github.io/vtk-js/docs/develop_requirement.html to install vtk, node and git.
I have been trying to integrate into a React aplication, and it outputs:
Failed to compile
./node_modules/vtk.js/Sources/Rendering/OpenGL/Texture/index.js
1126:25-47 "export 'default' (imported as 'ComputeGradientsWorker') was not found in './ComputeGradients.worker'
I just have used the code in: https://kitware.github.io/vtk-js/examples/PolyDataReader.html
In addition if I go to the previous file and deep into ./ComputedGradients.worker, I navigate well to ComputeGradients.worker.js.
Do I need other requirement to execute the aplication? I am using a node server.
In addition I have written the code as React code:
import React from 'react';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkFullScreenRenderWindow from 'vtk.js/Sources/Rendering/Misc/FullScreenRenderWindow/index';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import vtkPolyDataReader from 'vtk.js/Sources/IO/Legacy/PolyDataReader';
class LoadVTK extends React.Component() {
render() {
const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance();
const renderer = fullScreenRenderer.getRenderer();
const renderWindow = fullScreenRenderer.getRenderWindow();
const resetCamera = renderer.resetCamera;
const render = renderWindow.render;
const reader = vtkPolyDataReader.newInstance();
reader.setUrl(`C:\Users\YonePC\WebstormProjects\prototipo\src\components\animals\cabezasegmentado02.vtk`).then(() => {
const polydata = reader.getOutputData(0);
const mapper = vtkMapper.newInstance();
const actor = vtkActor.newInstance();
actor.setMapper(mapper);
mapper.setInputData(polydata);
renderer.addActor(actor);
resetCamera();
render();
});
return (
<div></div>
);
}
}
export default LoadVTK;
And I have used it from the main page as:
<LoadVTK/>
What could be the problem?

I had run your example and found two issues:
problem with dist path (already solved by #Jonathan Quiroz)
extends React.Component() instead of React.Component - which causes that code can be built, but can't be run properly in browser.
Don't forget to setup webpack properly (https://kitware.github.io/vtk-js/docs/intro_vtk_as_es6_dependency.html)
After these two updates it should work - I have already tested it.

you have to put the file in the server, for example i am running with webpack and the file is inside the folder dist:
dist/cabezasegmentado02.vtk
And when you call the file:
reader.setUrl("cabezasegmentado02.vtk")

Related

How to import lodash library in js file [duplicate]

I'd like to import this javascript package in React
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
However, there is no NPM package, so I can't import it as such:
import dwolla from 'dwolla'
or
import dwolla from 'https://cdn.dwolla.com/1/dwolla.js'
so whenver I try
dwolla.configure(...)
I get an error saying that dwolla is undefined. How do I solve this?
Thanks
Go to the index.html file and import the script
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
Then, in the file where dwolla is being imported, set it to a variable
const dwolla = window.dwolla;
This question is getting older, but I found a nice way to approach this using the react-helmet library which I feel is more idiomatic to the way React works. I used it today to solve a problem similar to your Dwolla question:
import React from "react";
import Helmet from "react-helmet";
export class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
myExternalLib: null
};
this.handleScriptInject = this.handleScriptInject.bind(this);
}
handleScriptInject({ scriptTags }) {
if (scriptTags) {
const scriptTag = scriptTags[0];
scriptTag.onload = () => {
// I don't really like referencing window.
console.log(`myExternalLib loaded!`, window.myExternalLib);
this.setState({
myExternalLib: window.myExternalLib
});
};
}
}
render() {
return (<div>
{/* Load the myExternalLib.js library. */}
<Helmet
script={[{ src: "https://someexternaldomain.com/myExternalLib.js" }]}
// Helmet doesn't support `onload` in script objects so we have to hack in our own
onChangeClientState={(newState, addedTags) => this.handleScriptInject(addedTags)}
/>
<div>
{this.state.myExternalLib !== null
? "We can display any UI/whatever depending on myExternalLib without worrying about null references and race conditions."
: "myExternalLib is loading..."}
</div>
</div>);
}
}
The use of this.state means that React will automatically be watching the value of myExternalLib and update the DOM appropriately.
Credit: https://github.com/nfl/react-helmet/issues/146#issuecomment-271552211
for typescript developers
const newWindowObject = window as any; // cast it with any type
let pushNotification = newWindowObject.OneSignal; // now OneSignal object will be accessible in typescript without error
You can't require or import modules from a URL.
ES6: import module from URL
What you can do is make an HTTP request to get the script content & execute it, as in the answer for how to require from URL in Node.js
But this would be a bad solution since your code compilation would depend on an external HTTP call.
A good solution would be to download the file into your codebase and import it from there.
You could commit the file to git if the file doesn't change much & are allowed to do it. Otherwise, a build step could download the file.
var _loaded = {};
function addScript(url) {
if (!loaded[url]) {
var s = document.createElement('script');
s.src = url;
document.head.appendChild(s);
_loaded[url] = true;
}
}
how to load javascript file from cdn server in a component
Add the script tag in your index.html and if you are using Webpack, you can use this webpack plugin https://webpack.js.org/plugins/provide-plugin/

What does `import type {Node} from 'react';` and usage in App: () => Node

Running this command:
npx react-native init AwesomeProject
In the App.js file I don't understand 2 lines:
import React from 'react';
import type {Node} from 'react'; // 1
import {
SafeAreaView,
ScrollView,
// ..... Code ....
const App: () => Node = () => { // 2
// ..... Code ....
export default App;
Importing type Node
Following Is there a point to doing 'import type' rather than 'import' with Flow?, I understand that such import is used to import a type of object, for instance:
import type { Array, Object, ... } from 'wherever';
To be honest I am more concerned on the next point (probably If I understand that I would automatically get the this as well).
const App: () => Node = () =>
All that I see is that App is a variable which references a function that returns an Object of type Node which this Object s also a function. Does it wrap the App into a 'React' instance or something?
What does const App: () => Node = () => do and why you would want to use it?
If we remove the types, the code is:
const App = () => {
// ... code
}
This is a react functional component.
Then on top of that is added a type: () => Node. This means it's a function that takes no parameters and returns a react Node. Types help with development by letting the computer analyze the code better, and point out bugs sooner (before even running the code)

Can I use face-recogition npm package in react?

I'm learning react and I'm trying to implement an npm package called face-recognition in my react project.
But it looks like that their documentation is for nodejs. I've looked into the source code of the package which seems that it doesn't export any module so I just imported it. But still, my console is giving me the error ModuleNotFoundError
Inshort: Can I use this face-recognition library in my react.js?
Here is my live code in codesandbox
Below is the raw code of the same file.
import React from "react";
import "face-recognition";
import image1 from "./assets/fFace.jpg";
import image2 from "./assets/mFace.jpg";
const Home = () => {
const imageOne = image1;
const win = new fr.ImageWindow();
// display image
win.setImage(imageOne);
const detector = fr.FaceDetector(imageOne);
// detect all faces
const faceRectangles = detector.locateFaces(imageOne);
return (
<>
<h1>Face Recognition</h1>
{faceRectangles}
</>
);
};
export default Home;
From the npm page
This package is pretty much obsolete. I recommend you to switch to face-api.js, which covers the same functionality as face-recognition.js in a nodejs as well as browser environment.

How to fix eslint errors in meteor with react tutorial

I've followed meteor tutorial, and when I finished I've decided to install eslint.
Now I see
Prefer default export import/prefer-default-export
for this line: export const Tasks = new Mongo.Collection('tasks'); in imports/api/tasks.js file. It contains also some Meteor methods. Here it is full source code: tasks.js.
I was trying to fix this eg. with
const Tasks = new Mongo.Collection('tasks');
export { Tasks as default };
But then browser stopped rendering the view.
Here is the server/main.js content, which imports tasks.js:
import '../imports/api/tasks.js';
How can I fix lint error without breaking applications functionality?
You could add an .eslintrc file to your project root and adapt the rule:
{"rules": {"import/prefer-default-export": ["off"]}}
UPDATE:
If you want to keep the rule, then you need to export Tasks as default like so:
const Tasks = new Mongo.Collection('tasks');
export default Tasks;
Now you have to change all the imports in the rest of your codebase from a named import to a default import. The named import looks like this
import { Tasks } from '/imports/api/tasks';
see e.g. here, whereas the new default import has to look like this
import Tasks from '/imports/api/tasks';
This should do it. Let me know if it works for you.

Import JSON file in React

I'm new to React and I'm trying to import a JSON DATA variable from an external file. I'm getting the following error:
Cannot find module "./customData.json"
Could some one help me? It works if I have my DATA variable in index.js but not when it's in an external JSON file.
index.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import customData from './customData.json';
import Profile from './components/profile';
import Hobbies from './components/hobbies';
class App extends Component {
render() {
return (
<div>
<Profile name={this.props.profileData.name}imgUrl={this.props.profileData.imgURL} />
<Hobbies hobbyList={this.props.profileData.hobbyList}/>
</div>
);
}
}
ReactDOM.render(<App profileData={DATA}/>, document.querySelector('.container'));
hobbies.js
import React, {Component} from 'react';
var Hobbies = React.createClass({
render: function(){
var hobbies = this.props.hobbyList.map(function(hobby, index){
return (<li key={index}>{hobby}</li>);
});
return (
<div>
<h5>My hobbies:</h5>
<ul>
{hobbies}
</ul>
</div>
);
}
});
export default Hobbies;
profile.js
import React from 'react';
var Profile = React.createClass({
render: function(){
return (
<div>
<h3>{this.props.name}</h3>
<img src={this.props.imgUrl} />
</div>
)
}
});
export default Profile
customData.json
var DATA = {
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
export default DATA
One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:
import Profile from './components/profile';
This answer explains more.
This old chestnut...
In short, you should be using require and letting node handle the parsing as part of the require call, not outsourcing it to a 3rd party module. You should also be taking care that your configs are bulletproof, which means you should check the returned data carefully.
But for brevity's sake, consider the following example:
For Example, let's say I have a config file 'admins.json' in the root of my app containing the following:
admins.json
[{
"userName": "tech1337",
"passSalted": "xxxxxxxxxxxx"
}]
Note the quoted keys, "userName", "passSalted"!
I can do the following and get the data out of the file with ease.
let admins = require('~/app/admins.json');
console.log(admins[0].userName);
Now the data is in and can be used as a regular (or array of) object.
With json-loader installed, you can use
import customData from '../customData.json';
or also, even more simply
import customData from '../customData';
To install json-loader
npm install --save-dev json-loader
Simplest approach is following
// Save this as someJson.js
const someJson = {
name: 'Name',
age: 20
}
export default someJson
then
import someJson from './someJson'
React 17 created from create-react-app, importing json just work by default.
import config from './config.json'
The solution that worked for me is that:-
I moved my data.json file from src to public directory.
Then used fetch API to fetch the file
fetch('./data.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory. So we have to explicitly move data.json file from src to public directory.
Please store your JSON file with the .js extension and make sure that your JSON should be in same directory.
// rename the .json file to .js and keep in src folder
Declare the json object as a variable
var customData = {
"key":"value"
};
Export it using module.exports
module.exports = customData;
From the component that needs it, make sure to back out two folders deep
import customData from '../customData';
In current react build you simply import and use:
import jsonData from 'path/to/myJson.json'
try with export default DATA or module.exports = DATA
there are multiple ways to do this without using any third-party code or libraries (the recommended way).
1st STATIC WAY: create a .json file then import it in your react component example
my file name is "example.json"
{"example" : "my text"}
the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.
How to import in react component
import myJson from "jsonlocation";
and you can use it anywhere like this
myJson.example
now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.
Now, what about if we want to dynamically import the JSON data? example a multi-language support website?
2 DYNAMIC WAY
1st declare your JSON file exactly like my example above
but this time we are importing the data differently.
let language = require('./en.json');
this can access the same way.
but wait where is the dynamic load?
here is how to load the JSON dynamically
let language = require(`./${variable}.json`);
now make sure all your JSON files are within the same directory
here you can use the JSON the same way as the first example
myJson.example
what changed? the way we import because it is the only thing we really need.
I hope this helps.
var langs={
ar_AR:require('./locale/ar_AR.json'),
cs_CZ:require('./locale/cs_CZ.json'),
de_DE:require('./locale/de_DE.json'),
el_GR:require('./locale/el_GR.json'),
en_GB:require('./locale/en_GB.json'),
es_ES:require('./locale/es_ES.json'),
fr_FR:require('./locale/fr_FR.json'),
hu_HU:require('./locale/hu_HU.json')
}
module.exports=langs;
Require it in your module:
let langs=require('./languages');
regards
This worked well in React 16.11.0
// in customData.js
export const customData = {
//json data here
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
// in index.js
import { customData } from './customData';
// example usage later in index.js
<p>{customData.name}</p>
My friends, if you are using React and TypeScript, just do these steps and DONE!
In the tsconfig.json add these 2 new lines:
// tsconfig.json
{
"compilerOptions": {
// ... other options
"esModuleInterop": true,
"resolveJsonModule": true
}
}
Import your json:
import yourJSON from "./data/yourJSON.json"
Something that worked for me was to simply place the JSON file in the public folder. You can simply import in any js using
brain.loadData("exampleFile.json");
It is as simple as that I guess. Definitely worth a try :D

Categories